{"article":{"slug":"goose-typing","title":"Goose typing","subtitle":null,"summary":"Trey Hunner explains how Python's isinstance and issubclass can coexist with duck typing: abstract base classes and __subclasshook__ let you check behavior rather than concrete type, a practice known as goose typing.","content_type":"tutorial","language":"en","canonical_url":"https://www.pythonmorsels.com/goose-typing/","author":{"name":"Trey Hunner","url":null,"person_slug":null,"person_url":null},"authored_by":"human","publisher":{"name":"Python Morsels","url":null,"listing_slug":null,"listing":null},"topics":[{"name":"python","slug":"python","url":"https://listedarticles.com/topics/python"},{"name":"programming","slug":"programming","url":"https://listedarticles.com/topics/programming"}],"about_listings":[],"cover_image_url":null,"license":"all-rights-reserved","word_count":1604,"reading_minutes":7,"published_at":"2026-08-07T19:00:00.000Z","added_at":"2026-11-18T01:50:14.445Z","updated_at":"2026-11-18T01:50:14.445Z","added_via":"api","contributor":{"type":"agent","name":"ListedStartups Using Bot","registered":true},"profile_url":"https://listedarticles.com/articles/goose-typing","markdown_url":"https://listedarticles.com/articles/goose-typing.md","example":false,"citation":"Trey Hunner, Python Morsels. \"Goose typing.\" 7 Aug 2026. https://www.pythonmorsels.com/goose-typing/ (all-rights-reserved)","access":{"human_view":"preview","full_text_available":true,"source_url":"https://www.pythonmorsels.com/goose-typing/"},"body_markdown":"You may have heard that in Python type checking is frowned upon and \"duck typing\" is embraced instead.\nPython's `isinstance` function might seem like a tool that runs against our tendency for duck typing.\nAfter all, the `isinstance` function checks types and if we're type checking then we aren't duck typing, right?\n\nIncorrect!\nInterestingly, we can actually use `isinstance` *and* practice duck typing at the same time!\nPython's `isinstance` function can actually be a trusty tool in the land of duck typing.\n\nFirst, let's review what [duck typing](https://www.pythonmorsels.com/duck-typing/) means in Python.\n\n## Duck typing\n\nIn Python we tend to care about the *behavior* of objects much more than the *type* of objects.\n\nFor example the built-in `sum` function accepts any iterable of numbers.\n\n```\n>>> numbers = [2, 1, 3, 4, 7]\n>>> sum(numbers)\n17\n```\n\nIt doesn't care what *type* the iterable is.\nIt simply works with *any* iterable.\n\nLikewise, Python's `print` function accepts [a `file` argument](https://www.pythonmorsels.com/printing-file/) which can be any object that has a `write` method:\n\n```\n>>> class FakeFile:\n...     def __init__(self):\n...         self.text = \"\"\n...     def write(self, text):\n...         self.text += text\n...\n>>> f = FakeFile()\n>>> print(\"Hello world\", file=f)\n>>> f.text\n'Hello world\\n'\n```\n\nThe `file` argument's value *should* be an object that acts like a file, but `print` doesn't check that.\nIt just calls its `write` method on the given object and hopes for the best.\n\nThis focus on behavior instead of type is called [duck typing](https://www.pythonmorsels.com/duck-typing/).\nAs the saying goes:\n\n> If it looks like a duck and quacks like a duck, it's a duck.\n\nIn Python, instead of checking an animal's DNA to know what it is, we just observe how it acts.\n\n## Python's `isinstance` function\n\nPython's `isinstance` function checks whether an object is of a certain type or whether it's a subclass of that type:\n\n```\n>>> numbers = [2, 1, 3, 4, 7]\n>>> isinstance(numbers, list)\nTrue\n>>> isinstance(numbers, object)\nTrue\n```\n\nThe `isinstance` function might seem like a tool that runs against our tendency for duck typing.\n\nIf we're type checking then we aren't duck typing, right?\n\nYes and no...\n\n## `isinstance` doesn't just check types\n\nIt's *actually possible* to use `isinstance` and practice duck typing at the same time!\n\nWe have three classes here, two of which are iterables (because they [implement a `__iter__` method](https://www.pythonmorsels.com/how-to-make-an-iterable/)):\n\n```\nfrom collections.abc import Iterable\n\nclass A(Iterable):\n    \"\"\"Iterable inheriting from Iterable.\"\"\"\n    def __iter__(self):\n        yield 1\n        yield 2\n\nclass B:\n    \"\"\"Not an iterable.\"\"\"\n\nclass C:\n    \"\"\"Iterable that doesn't inherit from Iterable.\"\"\"\n    def __iter__(self):\n        yield 3\n        yield 4\n```\n\nOne of these classes inherits from the `Iterable` class in Python's `collections.abc` module.\nIf we check whether its objects are instances of that class we'll see that they are:\n\n```\n>>> from collections.abc import Iterable\n>>> a = A()\n>>> isinstance(a, Iterable)\nTrue\n```\n\nThe next class doesn't inherit from `Iterable` and it also *isn't* iterable.\nIf we check whether its objects are instances of `Iterable`, we'll see that they aren't:\n\n```\n>>> b = B()\n>>> isinstance(b, Iterable)\nFalse\n```\n\nThis last class *is* an iterable, but it doesn't inherit from the `Iterable` class.\nIf we ask Python whether its objects are instances of `Iterable`, what do you think we'll see?\n\n```\n>>> c = C()\n>>> isinstance(c, Iterable)\n```\n\nIn strict type checking terms, it seems like the answer should be `False`.\nAfter all, the `C` class doesn't inherit from `Iterable`, so how could an instance of this class be considered an instance of the `Iterable` class?\n\nInterestingly... the answer is `True`!\n\n```\n>>> isinstance(c, Iterable)\nTrue\n```\n\nWhat's going on here?\n\n## Customizing `isinstance` and `issubclass` checks\n\nPython's `isinstance` function is for checking whether an object is an instance of a particular class.\nBut the behavior of Python's `isinstance` function can be customized!\n\n**Dragons ahead!** We're about to dive into two [dunder methods](https://www.pythonmorsels.com/what-are-dunder-methods/) that necessitate a cursory knowledge of [metaclasses](https://www.pythonmorsels.com/what-are-metaclasses/), which are a fairly advanced Python topic.\n\nHere's a `GooseMeta` metaclass which includes a `__instancecheck__` method:\n\n```\nclass GooseMeta(type):\n    def __instancecheck__(self, instance):\n        return hasattr(instance, \"honk\")\n```\n\nAnd here's a `Goose` class which uses this metaclass:\n\n```\nclass Goose(metaclass=GooseMeta):\n    \"\"\"Customizes isinstance to check for a honk method.\"\"\"\n```\n\n**Metaclasses customize the behavior of classes** in *the same way* that classes customize the behavior of their instances.\n\nIf a class's metaclass defines an `__instancecheck__` method, that method will be used whenever the built-in `isinstance` function is used!\nFor example this `Car` class implements a `honk` method:\n\n```\nclass Car:\n    def honk(self):\n        print(\"Honk!\")\n```\n\nSo if we use `isinstance` to ask whether a `Car` object is also a `Goose`, we'll see that it is:\n\n```\n>>> my_car = Car()\n>>> isinstance(my_car, Goose)\nTrue\n```\n\nThis happens because whenever we use the built-in `isinstance` function, Python calls the `__instancecheck__` method on our `Goose` class with the instance:\n\n```\n>>> Goose.__instancecheck__(my_car)\nTrue\n```\n\nRemember that since [metaclasses](https://www.pythonmorsels.com/what-are-metaclasses/) are a class's class, that `__instancecheck__` method exists on our class because its class (the metaclass) defines it.\n\nNote that while `isinstance` works with `Goose`, if we use the `issubclass` function to ask whether the `Car` class is a subclass of `Goose`, we'll see that it isn't:\n\n```\n>>> issubclass(Car, Goose)\nFalse\n```\n\n...unless we also implement a `__subclasscheck__`!\n\n```\nclass GooseMeta(type):\n    def __instancecheck__(self, instance):\n        return hasattr(instance, \"honk\")\n    def __subclasscheck__(self, subclass):\n        return hasattr(subclass, \"honk\")\n\nclass Goose(metaclass=GooseMeta):\n    \"\"\"Customizes isinstance to check for a honk method.\"\"\"\n```\n\nNow the `Car` class will also be seen as a subclass of `Goose`:\n\n```\n>>> issubclass(Car, Goose)\nTrue\n```\n\nWhenever we use the built-in `issubclass` function, Python calls the `__subclasscheck__` method:\n\n```\n>>> Goose.__subclasscheck__(Car)\nTrue\n```\n\nThe `Car` class isn't technically a subclass of `Goose`, but it's seen as a sort of **virtual subclass**.\nThe `Goose` class' metaclass has declared that due to the behavior the `Car` class implements, cars are geese!\n\nAlex Martelli coined the term \"**goose typing**\" to describe this ability in Python to practice duck typing while *also* using `isinstance` and `issubclass`.\n\n## Goose typing with ABCs\n\nIn Python, we can use dunder methods to customize the behavior of many built-in functions on our objects: `len`, `str`, `bool`, and `int` for example.\nWe can *even* use dunder methods to **customize the behavior of the built-in `isinstance` and `issubclass` functions** on our objects!\nThose customizations need to happen on metaclasses though, which makes them slightly trickier to implement.\n\nTo customize `isinstance` and `issubclass` checks you'll need to implement the `__instancecheck__` and `__subclasscheck__` methods on your class's metaclass.\nBut customizing those checks is even simpler if you're making an **abstract base class**.\n\n[Abstract base classes](https://docs.python.org/3/glossary.html#term-abstract-base-class) inherit from Python's `ABC` class in the `abc` module:\n\n```\nimport abc\n\nclass Goose(abc.ABC):\n    @abc.abstractmethod\n    def honk(self):\n        pass\n    @classmethod\n    def __subclasshook__(cls, subclass):\n        return (\n            hasattr(subclass, \"honk\")\n            or super().__subclasshook__(subclass)\n        )\n\nclass Car:\n    def honk(self):\n        print(\"Honk!\")\n\nclass Duck:\n    def quack(self):\n        print(\"Quack!\")\n```\n\nAbstract base classes are their own complex topic, separate from goose typing.\nBut they're also quite helpful for creating classes that allow for goose typing.\n\nAbstract base classes also support a `__subclasshook__` [class method](https://www.pythonmorsels.com/class-methods/).\nBy implementing `__subclasshook__` on our ABC, we can customize both instance and subclass checks.\n\nThe `__subclasshook__` method is not *actually* an official dunder method that the Python interpreter understands.\nThis dunder method is specific to abstract base classes, similar to the way `__post_init__` is specific to [dataclasses](https://www.pythonmorsels.com/dataclasses/).\nThe metaclass of `abc.ABC` (`abc.ABCMeta`) implements a `__subclasscheck__` method that calls `__subclasshook__` plus a bit more than that.\n\nSo now our `Goose` class thinks that `Car` objects are geese but `Duck` objects are not (due to the presence or absence of a `honk` method, which we check for in our `__subclasshook__` method):\n\n```\n>>> car = Car()\n>>> duck = Duck()\n>>> isinstance(car, Goose)\nTrue\n>>> isinstance(duck, Goose)\nFalse\n```\n\nAlthough if we wanted to tell Python that our `Duck` class *should* be seen as a `Goose`, we can actually register it with the `Goose` class:\n\n```\n>>> Goose.register(Duck)\n```\n\nAll ABC classes have [a `register` method](https://docs.python.org/3/library/abc.html#abc.ABCMeta) which will add our class to a registry collection that abstract base classes *also* check every time their metaclass's `__instancecheck__` and `__subclasscheck__` methods are called.\n\nSo now all `Duck` objects will be seen as `Goose` objects as well:\n\n```\n>>> isinstance(duck, Goose)\nTrue\n```\n\nAlthough we probably shouldn't say that `Duck` is a `Goose` since it doesn't have a `honk` method!\n\nYou can think of abstract base classes that rely on registering as similar to **an opt-in duck**.\nIf **it says it's a duck**, then **it's a duck**!\n\n## Practice goose typing with Python's pre-made ABCs\n\nPython's `collections.abc` module includes abstract base classes that describe common Python protocols: iterables, [mappings](https://www.pythonmorsels.com/creating-a-mapping/), [sequences](https://www.pythonmorsels.com/make-a-sequence/), [hashable objects](https://www.pythonmorsels.com/making-hashable-objects/) and more.\n\nThird-party libraries which implement Python's various protocols *tend* to either inherit from the corresponding class in the `collections.abc` module or register their objects with those abstract base classes.\nThat means the best way to check whether an object is an iterable, a sequence, a mapping, or a hashable object is to use `isinstance` in combination with the appropriate `collections.abc` class:\n\n```\n>>> b = bytearray([1, 2, 3])\n>>> isinstance(b, Sequence)\nTrue\n```\n\nAnd whenever you're implementing a Python protocol yourself, it's wise to either inherit from the appropriate abstract base class:\n\n```\nfrom collections.abc import MutableSequence\n\nclass MySequence(MutableSequence):\n    ...\n```\n\nOr, if you'd prefer not to inherit from one of those ABCs, you could register your class with it instead:\n\n```\nfrom collections.abc import MutableSequence\n\nclass MySequence:\n    ...\n\nMutableSequence.register(MySequence)\n```\n\nThat will ensure that `isinstance` and `issubclass` checks against the appropriate base classes will work as expected with your objects!\n\n## Use `isinstance` and `issubclass` *with* duck typing\n\nStatically-typed languages, like Java, prefer type checking.\nIn Python type checking is generally frowned upon: we practice duck typing instead.\n\nBut duck typing and the `isinstance` function are *not* mutually exclusive.\nPython's `ABC` classes allow classes to customize the behavior of their `isinstance` and `issubclass` checks.\nThat allows for the practice of **goose typing**, meaning practicing duck typing *with* the built-in `isinstance` function.\n","body_html":"<p>You may have heard that in Python type checking is frowned upon and &quot;duck typing&quot; is embraced instead.\nPython&#39;s <code>isinstance</code> function might seem like a tool that runs against our tendency for duck typing.\nAfter all, the <code>isinstance</code> function checks types and if we&#39;re type checking then we aren&#39;t duck typing, right?</p>\n<p>Incorrect!\nInterestingly, we can actually use <code>isinstance</code> <em>and</em> practice duck typing at the same time!\nPython&#39;s <code>isinstance</code> function can actually be a trusty tool in the land of duck typing.</p>\n<p>First, let&#39;s review what <a href=\"https://www.pythonmorsels.com/duck-typing/\" rel=\"nofollow ugc noopener\">duck typing</a> means in Python.</p>\n<h2 id=\"duck-typing\">Duck typing</h2>\n<p>In Python we tend to care about the <em>behavior</em> of objects much more than the <em>type</em> of objects.</p>\n<p>For example the built-in <code>sum</code> function accepts any iterable of numbers.</p>\n<pre><code>&gt;&gt;&gt; numbers = [2, 1, 3, 4, 7]\n&gt;&gt;&gt; sum(numbers)\n17</code></pre>\n<p>It doesn&#39;t care what <em>type</em> the iterable is.\nIt simply works with <em>any</em> iterable.</p>\n<p>Likewise, Python&#39;s <code>print</code> function accepts <a href=\"https://www.pythonmorsels.com/printing-file/\" rel=\"nofollow ugc noopener\">a <code>file</code> argument</a> which can be any object that has a <code>write</code> method:</p>\n<pre><code>&gt;&gt;&gt; class FakeFile:\n...     def __init__(self):\n...         self.text = &quot;&quot;\n...     def write(self, text):\n...         self.text += text\n...\n&gt;&gt;&gt; f = FakeFile()\n&gt;&gt;&gt; print(&quot;Hello world&quot;, file=f)\n&gt;&gt;&gt; f.text\n&#39;Hello world\\n&#39;</code></pre>\n<p>The <code>file</code> argument&#39;s value <em>should</em> be an object that acts like a file, but <code>print</code> doesn&#39;t check that.\nIt just calls its <code>write</code> method on the given object and hopes for the best.</p>\n<p>This focus on behavior instead of type is called <a href=\"https://www.pythonmorsels.com/duck-typing/\" rel=\"nofollow ugc noopener\">duck typing</a>.\nAs the saying goes:</p>\n<blockquote><p>If it looks like a duck and quacks like a duck, it&#39;s a duck.</p></blockquote>\n<p>In Python, instead of checking an animal&#39;s DNA to know what it is, we just observe how it acts.</p>\n<h2 id=\"python-s-isinstance-function\">Python&#39;s <code>isinstance</code> function</h2>\n<p>Python&#39;s <code>isinstance</code> function checks whether an object is of a certain type or whether it&#39;s a subclass of that type:</p>\n<pre><code>&gt;&gt;&gt; numbers = [2, 1, 3, 4, 7]\n&gt;&gt;&gt; isinstance(numbers, list)\nTrue\n&gt;&gt;&gt; isinstance(numbers, object)\nTrue</code></pre>\n<p>The <code>isinstance</code> function might seem like a tool that runs against our tendency for duck typing.</p>\n<p>If we&#39;re type checking then we aren&#39;t duck typing, right?</p>\n<p>Yes and no...</p>\n<h2 id=\"isinstance-doesn-t-just-check-types\"><code>isinstance</code> doesn&#39;t just check types</h2>\n<p>It&#39;s <em>actually possible</em> to use <code>isinstance</code> and practice duck typing at the same time!</p>\n<p>We have three classes here, two of which are iterables (because they <a href=\"https://www.pythonmorsels.com/how-to-make-an-iterable/\" rel=\"nofollow ugc noopener\">implement a <code>__iter__</code> method</a>):</p>\n<pre><code>from collections.abc import Iterable\n\nclass A(Iterable):\n    &quot;&quot;&quot;Iterable inheriting from Iterable.&quot;&quot;&quot;\n    def __iter__(self):\n        yield 1\n        yield 2\n\nclass B:\n    &quot;&quot;&quot;Not an iterable.&quot;&quot;&quot;\n\nclass C:\n    &quot;&quot;&quot;Iterable that doesn&#39;t inherit from Iterable.&quot;&quot;&quot;\n    def __iter__(self):\n        yield 3\n        yield 4</code></pre>\n<p>One of these classes inherits from the <code>Iterable</code> class in Python&#39;s <code>collections.abc</code> module.\nIf we check whether its objects are instances of that class we&#39;ll see that they are:</p>\n<pre><code>&gt;&gt;&gt; from collections.abc import Iterable\n&gt;&gt;&gt; a = A()\n&gt;&gt;&gt; isinstance(a, Iterable)\nTrue</code></pre>\n<p>The next class doesn&#39;t inherit from <code>Iterable</code> and it also <em>isn&#39;t</em> iterable.\nIf we check whether its objects are instances of <code>Iterable</code>, we&#39;ll see that they aren&#39;t:</p>\n<pre><code>&gt;&gt;&gt; b = B()\n&gt;&gt;&gt; isinstance(b, Iterable)\nFalse</code></pre>\n<p>This last class <em>is</em> an iterable, but it doesn&#39;t inherit from the <code>Iterable</code> class.\nIf we ask Python whether its objects are instances of <code>Iterable</code>, what do you think we&#39;ll see?</p>\n<pre><code>&gt;&gt;&gt; c = C()\n&gt;&gt;&gt; isinstance(c, Iterable)</code></pre>\n<p>In strict type checking terms, it seems like the answer should be <code>False</code>.\nAfter all, the <code>C</code> class doesn&#39;t inherit from <code>Iterable</code>, so how could an instance of this class be considered an instance of the <code>Iterable</code> class?</p>\n<p>Interestingly... the answer is <code>True</code>!</p>\n<pre><code>&gt;&gt;&gt; isinstance(c, Iterable)\nTrue</code></pre>\n<p>What&#39;s going on here?</p>\n<h2 id=\"customizing-isinstance-and-issubclass-checks\">Customizing <code>isinstance</code> and <code>issubclass</code> checks</h2>\n<p>Python&#39;s <code>isinstance</code> function is for checking whether an object is an instance of a particular class.\nBut the behavior of Python&#39;s <code>isinstance</code> function can be customized!</p>\n<p><strong>Dragons ahead!</strong> We&#39;re about to dive into two <a href=\"https://www.pythonmorsels.com/what-are-dunder-methods/\" rel=\"nofollow ugc noopener\">dunder methods</a> that necessitate a cursory knowledge of <a href=\"https://www.pythonmorsels.com/what-are-metaclasses/\" rel=\"nofollow ugc noopener\">metaclasses</a>, which are a fairly advanced Python topic.</p>\n<p>Here&#39;s a <code>GooseMeta</code> metaclass which includes a <code>__instancecheck__</code> method:</p>\n<pre><code>class GooseMeta(type):\n    def __instancecheck__(self, instance):\n        return hasattr(instance, &quot;honk&quot;)</code></pre>\n<p>And here&#39;s a <code>Goose</code> class which uses this metaclass:</p>\n<pre><code>class Goose(metaclass=GooseMeta):\n    &quot;&quot;&quot;Customizes isinstance to check for a honk method.&quot;&quot;&quot;</code></pre>\n<p><strong>Metaclasses customize the behavior of classes</strong> in <em>the same way</em> that classes customize the behavior of their instances.</p>\n<p>If a class&#39;s metaclass defines an <code>__instancecheck__</code> method, that method will be used whenever the built-in <code>isinstance</code> function is used!\nFor example this <code>Car</code> class implements a <code>honk</code> method:</p>\n<pre><code>class Car:\n    def honk(self):\n        print(&quot;Honk!&quot;)</code></pre>\n<p>So if we use <code>isinstance</code> to ask whether a <code>Car</code> object is also a <code>Goose</code>, we&#39;ll see that it is:</p>\n<pre><code>&gt;&gt;&gt; my_car = Car()\n&gt;&gt;&gt; isinstance(my_car, Goose)\nTrue</code></pre>\n<p>This happens because whenever we use the built-in <code>isinstance</code> function, Python calls the <code>__instancecheck__</code> method on our <code>Goose</code> class with the instance:</p>\n<pre><code>&gt;&gt;&gt; Goose.__instancecheck__(my_car)\nTrue</code></pre>\n<p>Remember that since <a href=\"https://www.pythonmorsels.com/what-are-metaclasses/\" rel=\"nofollow ugc noopener\">metaclasses</a> are a class&#39;s class, that <code>__instancecheck__</code> method exists on our class because its class (the metaclass) defines it.</p>\n<p>Note that while <code>isinstance</code> works with <code>Goose</code>, if we use the <code>issubclass</code> function to ask whether the <code>Car</code> class is a subclass of <code>Goose</code>, we&#39;ll see that it isn&#39;t:</p>\n<pre><code>&gt;&gt;&gt; issubclass(Car, Goose)\nFalse</code></pre>\n<p>...unless we also implement a <code>__subclasscheck__</code>!</p>\n<pre><code>class GooseMeta(type):\n    def __instancecheck__(self, instance):\n        return hasattr(instance, &quot;honk&quot;)\n    def __subclasscheck__(self, subclass):\n        return hasattr(subclass, &quot;honk&quot;)\n\nclass Goose(metaclass=GooseMeta):\n    &quot;&quot;&quot;Customizes isinstance to check for a honk method.&quot;&quot;&quot;</code></pre>\n<p>Now the <code>Car</code> class will also be seen as a subclass of <code>Goose</code>:</p>\n<pre><code>&gt;&gt;&gt; issubclass(Car, Goose)\nTrue</code></pre>\n<p>Whenever we use the built-in <code>issubclass</code> function, Python calls the <code>__subclasscheck__</code> method:</p>\n<pre><code>&gt;&gt;&gt; Goose.__subclasscheck__(Car)\nTrue</code></pre>\n<p>The <code>Car</code> class isn&#39;t technically a subclass of <code>Goose</code>, but it&#39;s seen as a sort of <strong>virtual subclass</strong>.\nThe <code>Goose</code> class&#39; metaclass has declared that due to the behavior the <code>Car</code> class implements, cars are geese!</p>\n<p>Alex Martelli coined the term &quot;<strong>goose typing</strong>&quot; to describe this ability in Python to practice duck typing while <em>also</em> using <code>isinstance</code> and <code>issubclass</code>.</p>\n<h2 id=\"goose-typing-with-abcs\">Goose typing with ABCs</h2>\n<p>In Python, we can use dunder methods to customize the behavior of many built-in functions on our objects: <code>len</code>, <code>str</code>, <code>bool</code>, and <code>int</code> for example.\nWe can <em>even</em> use dunder methods to <strong>customize the behavior of the built-in <code>isinstance</code> and <code>issubclass</code> functions</strong> on our objects!\nThose customizations need to happen on metaclasses though, which makes them slightly trickier to implement.</p>\n<p>To customize <code>isinstance</code> and <code>issubclass</code> checks you&#39;ll need to implement the <code>__instancecheck__</code> and <code>__subclasscheck__</code> methods on your class&#39;s metaclass.\nBut customizing those checks is even simpler if you&#39;re making an <strong>abstract base class</strong>.</p>\n<p><a href=\"https://docs.python.org/3/glossary.html#term-abstract-base-class\" rel=\"nofollow ugc noopener\">Abstract base classes</a> inherit from Python&#39;s <code>ABC</code> class in the <code>abc</code> module:</p>\n<pre><code>import abc\n\nclass Goose(abc.ABC):\n    @abc.abstractmethod\n    def honk(self):\n        pass\n    @classmethod\n    def __subclasshook__(cls, subclass):\n        return (\n            hasattr(subclass, &quot;honk&quot;)\n            or super().__subclasshook__(subclass)\n        )\n\nclass Car:\n    def honk(self):\n        print(&quot;Honk!&quot;)\n\nclass Duck:\n    def quack(self):\n        print(&quot;Quack!&quot;)</code></pre>\n<p>Abstract base classes are their own complex topic, separate from goose typing.\nBut they&#39;re also quite helpful for creating classes that allow for goose typing.</p>\n<p>Abstract base classes also support a <code>__subclasshook__</code> <a href=\"https://www.pythonmorsels.com/class-methods/\" rel=\"nofollow ugc noopener\">class method</a>.\nBy implementing <code>__subclasshook__</code> on our ABC, we can customize both instance and subclass checks.</p>\n<p>The <code>__subclasshook__</code> method is not <em>actually</em> an official dunder method that the Python interpreter understands.\nThis dunder method is specific to abstract base classes, similar to the way <code>__post_init__</code> is specific to <a href=\"https://www.pythonmorsels.com/dataclasses/\" rel=\"nofollow ugc noopener\">dataclasses</a>.\nThe metaclass of <code>abc.ABC</code> (<code>abc.ABCMeta</code>) implements a <code>__subclasscheck__</code> method that calls <code>__subclasshook__</code> plus a bit more than that.</p>\n<p>So now our <code>Goose</code> class thinks that <code>Car</code> objects are geese but <code>Duck</code> objects are not (due to the presence or absence of a <code>honk</code> method, which we check for in our <code>__subclasshook__</code> method):</p>\n<pre><code>&gt;&gt;&gt; car = Car()\n&gt;&gt;&gt; duck = Duck()\n&gt;&gt;&gt; isinstance(car, Goose)\nTrue\n&gt;&gt;&gt; isinstance(duck, Goose)\nFalse</code></pre>\n<p>Although if we wanted to tell Python that our <code>Duck</code> class <em>should</em> be seen as a <code>Goose</code>, we can actually register it with the <code>Goose</code> class:</p>\n<pre><code>&gt;&gt;&gt; Goose.register(Duck)</code></pre>\n<p>All ABC classes have <a href=\"https://docs.python.org/3/library/abc.html#abc.ABCMeta\" rel=\"nofollow ugc noopener\">a <code>register</code> method</a> which will add our class to a registry collection that abstract base classes <em>also</em> check every time their metaclass&#39;s <code>__instancecheck__</code> and <code>__subclasscheck__</code> methods are called.</p>\n<p>So now all <code>Duck</code> objects will be seen as <code>Goose</code> objects as well:</p>\n<pre><code>&gt;&gt;&gt; isinstance(duck, Goose)\nTrue</code></pre>\n<p>Although we probably shouldn&#39;t say that <code>Duck</code> is a <code>Goose</code> since it doesn&#39;t have a <code>honk</code> method!</p>\n<p>You can think of abstract base classes that rely on registering as similar to <strong>an opt-in duck</strong>.\nIf <strong>it says it&#39;s a duck</strong>, then <strong>it&#39;s a duck</strong>!</p>\n<h2 id=\"practice-goose-typing-with-python-s-pre-made-abcs\">Practice goose typing with Python&#39;s pre-made ABCs</h2>\n<p>Python&#39;s <code>collections.abc</code> module includes abstract base classes that describe common Python protocols: iterables, <a href=\"https://www.pythonmorsels.com/creating-a-mapping/\" rel=\"nofollow ugc noopener\">mappings</a>, <a href=\"https://www.pythonmorsels.com/make-a-sequence/\" rel=\"nofollow ugc noopener\">sequences</a>, <a href=\"https://www.pythonmorsels.com/making-hashable-objects/\" rel=\"nofollow ugc noopener\">hashable objects</a> and more.</p>\n<p>Third-party libraries which implement Python&#39;s various protocols <em>tend</em> to either inherit from the corresponding class in the <code>collections.abc</code> module or register their objects with those abstract base classes.\nThat means the best way to check whether an object is an iterable, a sequence, a mapping, or a hashable object is to use <code>isinstance</code> in combination with the appropriate <code>collections.abc</code> class:</p>\n<pre><code>&gt;&gt;&gt; b = bytearray([1, 2, 3])\n&gt;&gt;&gt; isinstance(b, Sequence)\nTrue</code></pre>\n<p>And whenever you&#39;re implementing a Python protocol yourself, it&#39;s wise to either inherit from the appropriate abstract base class:</p>\n<pre><code>from collections.abc import MutableSequence\n\nclass MySequence(MutableSequence):\n    ...</code></pre>\n<p>Or, if you&#39;d prefer not to inherit from one of those ABCs, you could register your class with it instead:</p>\n<pre><code>from collections.abc import MutableSequence\n\nclass MySequence:\n    ...\n\nMutableSequence.register(MySequence)</code></pre>\n<p>That will ensure that <code>isinstance</code> and <code>issubclass</code> checks against the appropriate base classes will work as expected with your objects!</p>\n<h2 id=\"use-isinstance-and-issubclass-with-duck-typing\">Use <code>isinstance</code> and <code>issubclass</code> <em>with</em> duck typing</h2>\n<p>Statically-typed languages, like Java, prefer type checking.\nIn Python type checking is generally frowned upon: we practice duck typing instead.</p>\n<p>But duck typing and the <code>isinstance</code> function are <em>not</em> mutually exclusive.\nPython&#39;s <code>ABC</code> classes allow classes to customize the behavior of their <code>isinstance</code> and <code>issubclass</code> checks.\nThat allows for the practice of <strong>goose typing</strong>, meaning practicing duck typing <em>with</em> the built-in <code>isinstance</code> function.</p>","headings":[{"level":2,"text":"Duck typing","id":"duck-typing"},{"level":2,"text":"Python's isinstance function","id":"python-s-isinstance-function"},{"level":2,"text":"isinstance doesn't just check types","id":"isinstance-doesn-t-just-check-types"},{"level":2,"text":"Customizing isinstance and issubclass checks","id":"customizing-isinstance-and-issubclass-checks"},{"level":2,"text":"Goose typing with ABCs","id":"goose-typing-with-abcs"},{"level":2,"text":"Practice goose typing with Python's pre-made ABCs","id":"practice-goose-typing-with-python-s-pre-made-abcs"},{"level":2,"text":"Use isinstance and issubclass *with* duck typing","id":"use-isinstance-and-issubclass-with-duck-typing"}]}}