Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Other unique-instance objects besides None in python?

The python language reference mentions three objects which have a single, unique instance: None, NotImplemented, and Ellipsis (section 3.2 "The Standard Type Hierarchy"). The test x is None is a common idiom made possible by the guaranteed uniqueness of None. I cannot find any other mention of unique-instance objects, either in python documentation or on stack overflow. A few questions, like this one have interesting suggestions for ways to construct such objects, but what I want to know is whether there are any beyond these three built-ins that I've missed.

For example, () appears to be unique (in admittedly very limited testing in CPython), so is the test x is () safe? Or is x == () mandatory for this case?

like image 558
David Munro Avatar asked Sep 13 '25 20:09

David Munro


1 Answers

Well... you can think of any global object as being "unique" in the sense that it is always the same object.

For example:

>>> x = file
>>> x is file
True
>>> x = True
>>> x is True
True
>>> x = ZeroDivisionError
>>> x is ZeroDivisionError
True

There is nothing special about:

>>> x = None
>>> x is None
True

What you are probably wondering is why you should test x is None rather than x == None.

The answer is: x == None will call x.__eq__(None) which may return True in all sorts of situations where x is not actually None (although in reality that is not very common).

Instance?

Well, you may say there is a difference: None is an instance.

Well, the truth is, everything in Python is an object, which means everything is an instance. In my examples, file and ZeroDivisionError are instances of type, True is instance of bool and None is instance of NoneType (note that type is an instance of type, so there are no exceptions to the rule).

There is one special thing about None - it is the only instance of NoneType and you cannot make others (unless there is some good trick?)

But that is actually a property of NoneType - it does not let you make new instances:

TypeError: cannot create 'NoneType' instances

But that is not really essential for the whole story.

EDIT These "unique-instance objects" are called singletons. You can make some of yours, of course.

like image 52
zvone Avatar answered Sep 15 '25 10:09

zvone