How to document a duck type?

More strictly typed languages, like Java, have the concept of "interfaces": collections of methods that any class implementing the interface is supposed to provide.

I suppose you could borrow the concept without necessarily bringing along the baggage of strict typing: just define and document an abstract class Foo, and then say that your method expects "a Foo or a Foo-like object". You don't even have to make any other class actually inherit from Foo if you don't want to; people reading the documentation will still know where to go to find out what is expected of a Foo-like object.


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).


The point of duck typing is that the notion of "type" becomes an abstract intuitive idea, rather than something that is formally part of the language. This makes typing much more fluid and flexible than in languages where type checking is part of the language.

What is required when using duck typing is not that the program knows what "type" you're using, but that other programmers do. So if you have a whole family of classes/functions/etc that operate on objects of a particular "type", and that type is not able to be described in a few words, just add a section in comments or a docstring (or even an external .txt file) describing your type and naming it. Then you can just refer to that name everywhere.