I’m having documentation bloat on me, as anytime I encounter a complex duck-type, I need some way to say “this duck type” but instead get caught in an endless cycle of “your function requires this of this input, but doesn’t document it”, and then documenting it. This results in bloated, repetitive documentation, such as the following:
def Foo(arg):
"""
Args:
arg: An object that supports X functionality, and Y functionality,
and can be passed to Z other functionality.
"""
# Insert code here.
def Bar(arg):
"""
Args:
arg: An object that supports X functionality, and Y functionality,
and can be passed to Z other functionality.
"""
# Insert code here.
And so on, and so on, for Baz, Qux, and other functions. I need some shorter way of writing “arg is a (type of object)”.
For some duck types, it’s as easy as “A dict-like object”: we know what we expect of a dict, and so, we know what to pass. A dict, or something that can mimic it.
I feel C++ has this same problem with templated types. Haskell would have it, but one can use a type class’s definition to document it. (Note: Haskell classes != classes in Java/C++/Python/etc.) (Note: I don’t really program in Haskell, so forgive me if it is a crappy example.)
Should I go the traditional OO route, and just write a base class, and say, “anything like this base class” in the docs? The code wouldn’t enforce deriving from the base class (as there is no requirement for the object to be derived from it), and the base class adds no value except to document the properties of the interface, essentially.
On the other hand, I’m programming Python, and I try to program within the idioms of a language. (As doing otherwise usually hurts.) Base classes are good for inheriting functionality, but when your base class is completely abstract, it doesn’t seem to add value in a duck-typed language.
EDIT: To the answers: I know what duck typing is (that should be evident from the post). Where do I document it is the question, esp. when no class exists to attach documentation to.
The idea behind duck typing is that you document that you are expecting a duck, and it is up to other objects to fake being a duck.
Nowhere in the docs does any API specify that it accepts a StringIO object; however, we can use them in most places that expect a “file-like object”.
Also, for the most part, the standard library tries to avoid naming the specific methods demanded of a duck type. That leaves the implementation open to change. The random.sample API, for example, could have been defined in terms of iterables or in terms of sequences.
If you want to be more specific than this, you could use abstract base classes. Several are already included in the collections module (such as Iterable, Hashable, and Sized) or numbers module (Rational, Integral, etc). It is not hard to model after those to write your own. Then, the documentation simply mentions which ABCs are required (e.g. x is a Sized Iterable and y is an Integral).