Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are Python Empty Immutables Singletons?

Are Python Empty Immutables Singletons?

If you review the CPython implementation of builtin types, you'll find comments on all the immutable builtin objects that their empty versions are singletons. This would make a lot of sense as Python could avoid wasting memory on redundant items that would never change in place.

Here, specifically, is the source for 2.6 that references frozensets. It declares as a comment:

/* The empty frozenset is a singleton */

I find the same comment in CPython 2.5 as well. I think it makes sense to refer to the source in addition to the documentation because CPython is the reference implementation of Python.

I'm using Python 2.6.5, and I get the following result in my interpreter:

>>> g = frozenset()
>>> f = frozenset('a') - frozenset('a')
>>> f
frozenset([])
>>> f is g
False
>>> id(f)
279262312
>>> id(g)
114734544

Does this mean that the comment is wrong? Is this a bug in 2.6.5? Is this guaranteed in later versions of Python? If so, I can't find reference to it in the documentation.

I ask this because I need a check that was identical to membership in (None, ''), but the reason is another story.

Is this why it's considered best practice to use is to check for None, and to use == or Python's semantic Falsiness of empty types for control flow relating to other types?

To sum up:

Are Python's empty immutables ever guaranteed to be singletons?

like image 558
Russia Must Remove Putin Avatar asked Aug 12 '14 20:08

Russia Must Remove Putin


1 Answers

The description of standard types makes no promise that equivalent objects are identical, except for True, False, None, NotImplemented, and Ellipsis. Some of the promises that it does not make are() is (), nor 1 is 1, nor 'hello' is 'hello'. (In fact, the documentation specifically denies the requirement 1 is 1 in the final paragraph of 3.1.)

No, Python's empty immutable containers are not guaranteed to be singletons*. The only guaranteed singletons are True, False, None, NotImplemented, and Ellipsis.



* Note: the word "singleton" in this context is used other than in its generally accepted meaning. In this post, singleton means a value that can be held by only one object; it follows that every object containing that value is identical.
like image 69
Robᵩ Avatar answered Sep 28 '22 07:09

Robᵩ