Duplicate None or Other Python Cigletons
First of all: this question covers almost zero use cases and is only about curiosity. It is said:
I started wondering not too long ago if it was possible to duplicate an object None
from Python (or any other singleton like True
or Ellipsis
). By "duplicate" I mean creating an exact copy that is not another reference to the same object. I.e:
>>> noneBis == None
True
>>> noneBis is None
False
Why I think this would be possible, because of the basic philosophy of Python: Everything is an object . And the object can be copied.
I tried several ways (even more confusing than others) and couldn't do it:
>>> copy.deepcopy(None) is None
True
>>> types.NoneType()
TypeError: cannot create NoneType instances
>>> object.__new__(type(None))
TypeError: object.__new__(NoneType) is not safe, use NoneType.__new__()
>>> types.NoneType.__new__(types.NoneType)
TypeError: object.__new__(NoneType) is not safe, use NoneType.__new__()
This seems like a pretty fierce and insane scientist, but I'm not sure if I tried hard enough. (I tested this in Python 2.7, but since Python 3+ was designed to be even more reliable than Python 2, I don't think the results will be better.)
Can you create a separate duplicate Python singleton?
source to share
If you could create a "duplicate copy" of one single, it wouldn't be superfluous, would it?
wrt / builtin singletons (for example None
) that are implemented in C (or whatever the language for a given implementation), I don't think you can ever expect to "clone" them, except for both the Python fork and some similarly extreme method. Also note that since the Python language specs explicitly guarantee that None
is single, this will no longer be Python;)
Now if all you want is a single and is compared to None
rather than None
, here's a possible (python 2.7.x):
def __mknone():
_instance = [None]
class NotNoneType(object):
def __new__(cls):
if _instance[0] is not None:
raise TypeError("cannot create 'NotNoneType' instances")
_instance[0] = object.__new__(cls)
return _instance[0]
def __eq__(self, other):
if other is None:
return True
return other == _instance[0]
def __nonzero__(self):
return False
return NotNoneType()
NotNone = __mknone()
NotNoneType = type(NotNone)
del __mknone
Tell me if you manage to create another NotNoneType
BTW instance ;)
source to share