Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a non-object exist in Python?

As everyone knows, everything is an object in Python. What I'm wondering about is whether it's possible to create an "object" x such that isinstance(x, object) returns False. I suspect it's possible with sufficient abuse of the CPython API, though achieving this with pure Python would be even more interesting.

Initially I thought that old-style classes would return False since the object hierarchy might not fully apply, but it seems like isinstance(x, object) is indeed True for instances of old-style classes.

While this is mostly of theoretical interest, it might be interesting (or dangerous) if Python allows the creation of a new object hierarchy disconnected from the base object type.

like image 470
nneonneo Avatar asked Sep 28 '22 21:09

nneonneo


2 Answers

Of course you can do everything via the C API (in particular via the awesome forbiddenfruit module)

>>> from forbiddenfruit import curse
>>> class C: pass
... 
>>> curse(type, "__instancecheck__", lambda cls, obj: type(obj) != C)
>>> isinstance(C(), object)
False
>>> isinstance(C(), C)
True
like image 55
antony Avatar answered Oct 22 '22 16:10

antony


From the docs, chapter 3 (Data Model): "All data in a Python program is represented by objects." Seems clear enough. You say the alternative "might be interesting" but there are already lots of interesting things that aren't Python.

like image 38
Paul Cornelius Avatar answered Oct 22 '22 14:10

Paul Cornelius