Search code examples
pythoncons

How do I create a unique object?


I want

class MyClass(object):
    _my_unique = ????      # if this were lisp, I would have written (cons nil nil) here

    def myFunc (self, arg):
        assert arg != _my_unique    # this must never fail
        ...

What do use instead of ??? to ensure that the assert never fails?

(With Lisp, I could create _my_unique with (cons nil nil) and used eq in assert).

PS. Use case: I will put _my_unique in a dict, so I want it to be equal to itself, but I do not want it to be equal (in the dict collision sense) to anything passed in from the outside.


Solution

  • You can use object(), but this won't make the assert "never fail". It will still fail if you call myFunc and pass MyClass.my_unique as the object. Also, if you want to test whether it's the same object, use arg is not my_unique rather than !=.