views:

91

answers:

2

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).

+1  A: 

Yes. This is a good way to define unique constants. There is of course, the minimal risk of whatever object you are comparing it to being defined as equal to everything, but if everyone is playing reasonably nicely, this should work. Also, the garbage collection issue won't be a problem, because if that should ever happen, your constant has already gone away, and isn't around to compare equal to the new object with the same id.

jcdyer
Hmm, that's an interesting point. I never considered that some other object might "violate" equality like that. I can't find a "special method" for the `id()` built-in function, I wonder if `id(MY_CONSTANT) == id(someOtherVariable)` can be "tricked" in this way...
Matt Joiner
@Matt, `id(MY_CONSTANT) == id(someOtherVariable)` is equivalent (but slower) to `MY_CONSTANT is someOtherVariable`. I would usually reverse that to `someOtherVariable is MY_CONSTANT` for readability
gnibbler
A: 

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

gnibbler
well... all the effort was done in jcd's answer, but this is the one i'd want to see
Matt Joiner