hn.today

Goose Typing – Python Morsels

pythonmorsels.com13 points0 comments
Screenshot of Goose Typing – Python Morsels

Duck typing means Python code usually relies on what an object can do rather than its exact class: `sum` accepts any suitable iterable, and `print` can write to any object with a `write` method. This can seem at odds with `isinstance` and `issubclass`, but Python lets classes customize those checks. A metaclass can define `__instancecheck__` and `__subclasscheck__` so an object or class qualifies based on behavior - for example, treating anything with a `honk` method as a “Goose.” Such objects are virtual instances or subclasses, even without inheriting from Goose. This combination of behavioral compatibility and type checks is called goose typing.

The more practical route is to use abstract base classes (ABCs). An ABC can define `__subclasshook__` to recognize classes by their methods, and it can explicitly register classes that should count even if they do not meet that structural test. Registration is an opt-in declaration, so it should be used only when the class genuinely belongs to the protocol. Python’s `collections.abc` module provides ready-made ABCs for protocols such as iterables, sequences, mappings, and hashable objects. Code can check these with `isinstance`, while implementations can inherit from the relevant ABC or register with it. The central point is that `isinstance` need not enforce rigid inheritance: used with ABCs, it can support duck typing and provide useful protocol checks.

Read on pythonmorsels.com0 comments on Hacker News

Summary generated by AI from the linked article. hn.today is not affiliated with Hacker News or Y Combinator.

More in Programming

The daily digest

Today's best Hacker News stories, summarized and screenshotted, one email a day.