How Python’s isinstance Works Under the Hood: Overloading and Duck Typing
This article explains the internal algorithm of Python's isinstance function, how it can be overloaded via __instancecheck__, the role of metaclasses, and provides concrete code examples and a step‑by‑step recreation of the check logic for better understanding of duck typing.
Python's built‑in isinstance() can be overloaded via the __instancecheck__ special method, which the CPython implementation looks for before applying its default logic.
According to PEP 3119, the check first sees whether the class defines __instancecheck__ and, if so, calls it; otherwise it falls back to the normal subclass test.
class Sizeable(object):
def __instancecheck__(cls, instance):
print("__instancecheck__ call")
return hasattr(instance, "__len__")Running isinstance(b, Sizeable) where b is an instance of a plain class B prints False because the fast‑path exact‑type test bypasses __instancecheck__.
The CPython source in abstract.c shows the algorithm: a quick exact‑type match, a check for PyType_CheckExact, then a lookup of __instancecheck__ via _PyObject_LookupSpecial, and finally a call to the found method.
If the class is created directly by type, the fast path returns true when the instance’s type matches; otherwise the code walks the MRO tuple to see if the class appears.
To make isinstance(x, C) use a custom rule you must:
Ensure x is not a direct instance of C.
Define a metaclass for C.
Implement __instancecheck__ in that metaclass.
Example with a metaclass:
class MetaSizeable(type):
def __instancecheck__(cls, instance):
print("__instancecheck__ call")
return hasattr(instance, "__len__")
class Sizeable(metaclass=MetaSizeable):
passNow isinstance([], Sizeable) returns True while isinstance(b, Sizeable) returns False, demonstrating how duck‑typing can be expressed through an overloaded isinstance.
The article also provides a pure‑Python recreation of the logic in the function _isinstance, showing the five steps the interpreter follows.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
