6

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.

maaku
  • 163
  • 4
  • Everything is an instance of `object`. There is trickery at the C-level to make even `type(object)` an instance of object. I don't have a reference right now but there was a blog post out there sometime in the last six months about this. – agf Mar 09 '12 at 20:00

2 Answers2

1

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
Ethan Furman
  • 63,992
  • 20
  • 159
  • 237
  • Hrm.. but any pure-python type will always derive from object? That might be good enough, as long as its also true of commonly used/standard library C modules (cStringIO, cDecimal, etc.) – maaku Mar 09 '12 at 20:04
  • Unless they are still using the old style classes -- but if that distinction is not important your `__subclasshook__` can ignore it (as the example does). – Ethan Furman Mar 09 '12 at 20:10
  • Awesome! That looks like the ideal solution for `Alpha`. Thanks Ethan! – maaku Mar 09 '12 at 20:26
0

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

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358