How to document a duck type?

前端 未结 3 1961
迷失自我
迷失自我 2021-01-17 10:44

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 \"

3条回答
  •  [愿得一人]
    2021-01-17 10:59

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

提交回复
热议问题