[Python-3000] Why isinstance() and issubclass() don't need to be unforgeable

Guido van Rossum guido at python.org
Tue May 1 19:07:31 CEST 2007

On 5/1/07, Phillip J. Eby <pje at telecommunity.com> wrote:
> I just wanted to throw in a note for those who are upset with the idea that
> classes should be able to decide how isinstance() and issubclass()
> work.  If you want "true, unforgeable" isinstance and subclass, you can
> still use these formulas:
> def true_issubclass(C1, C2):
>      return C2 in type.__mro__.__get__(C1)
> def isinstance_no_proxy(o, C):
>      return true_issubclass(type(o), C)
> def isinstance_with_proxy(o, C):
>      cls = getattr(o, '__class__', None)
>      return true_issubclass(cls, C) or isinstance_no_proxy(o, C)
> Their complexity reflects the fact that they rely on implementation details
> which the vast majority of code should not care about.
> So, if you really have a need to find out whether something is truly an
> instance of something for *structural* reasons, you will still be able to
> do that.  Yes, it will be a pain.  But deliberately inducing structural
> dependencies *should* be painful, because you're making it painful for the
> *users* of your code, whenever you impose isinstance/issubclass checks
> beyond necessity.
> The fact that it's currently *not* painful, is precisely what makes it such
> a good idea to add the new hooks to make these operations forgeable.
> The default, in other words, should not be to care about what objects
> *are*, only what they *claim* to be.

(Or what is claimed about them!)

Thanks for writing this note!

--Guido van Rossum (home page: http://www.python.org/~guido/)

More information about the Python-3000 mailing list