Search code examples
pythoncomparisonuniqueconstantscpython

Assign a value equal only to itself


I wish to assign to a variable (a "constant"), a value that will allow that variable to only ever return True in is and == comparisons against itself.

I want to avoid assigning an arbitary value such as an int or some other type on the off chance that the value I choose clashes with some other.

I'm considering generating an instance of a class that uses the uniqueness of CPython's id() values in any comparisons the value might support.

From here:

If no __cmp__(), __eq__()  or __ne__()  operation is defined, class instances are compared by object identity (“address”).

Would suggest that:

MY_CONSTANT = object()

Will only ever return true in a comparison with MY_CONSTANT on a CPython implementation if MY_CONSTANT was somehow garbage collected, and something else allocated in it's place during the comparison (I would assume this is probably never going to happen).


Solution

  • As long as MY_CONSTANT stays in scope the object it references can not be garbage collected. You really should always use is for comparison, as the behaviour of == can be overridden