Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any value in Python for which isinstance(value, object) is not True?

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.

like image 856
maaku Avatar asked Mar 09 '12 19:03

maaku


1 Answers

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
like image 161
Ethan Furman Avatar answered Oct 02 '22 19:10

Ethan Furman