Question

It is my understanding that since type/class unification every value is of a type that derives from object. However I can't find absolute confirmation of this in the docs. While it stands to reason that isinstance(anything, object) should always be True, I could also imagine there being legacy edge cases in the Python 2 codebase. Does anyone know of an example where isinstance(value, object) is not True?

Context: as part of a type hierarchy I'm designing, there's an all-encompasing Alpha type for which I want isinstance(obj, Alpha) to always return True. I'm thinking that on Python 2.6+ ABCMeta.register(object) should do the trick, but I want to be sure.

EDIT: For posterity's sake, ABCMeta.register(object) will not work (try it). Ethan Furman provides an alternative solution for this case in his answer below.

Was it helpful?

Solution

It is possible to create classes in non-Python code (C, for example) that do not derive from object.

You should be able to achieve what you want by adding __subclasshook__ to your Alpha:

--> import abc
--> class Test(object):
...   __metaclass__ = abc.ABCMeta
...   @classmethod
...   def __subclasshook__(cls, C):
...     return True
...
--> isinstance(dict(), Test)
True
--> isinstance(42, Test)
True
--> isinstance(0.59, Test)
True
--> class old_style:
...     pass
...
--> isinstance(old_style(), Test)
True

OTHER TIPS

In 2.x, user-defined classes (and a few stdlib classes) do not derive from object by default. This is fixed in 3.x.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top