Home Ask Login Register

Developers Planet

Your answer is one click away!

kelvinsong February 2016

Python: will id() always be nonzero?

I’m wondering if there is anything about python object IDs that will prevent them from ever equaling zero? I’m asking because I’m using zero as a stand-in for a special case in my code.


Foon February 2016

This isn't as strong an answer as I'd like, but doing help(id) on python 2.7.5

id(...) id(object) -> integer

Return the identity of an object.  This is guaranteed to be unique among
simultaneously existing objects.  (Hint: it's the object's memory address.)

Assuming you don't have an object that is pointing to NULL, you should be safe there.

Wombatz February 2016

From the docs

CPython implementation detail: This is the address of the object in memory.

0 is an invalid memory location. So no object in C will ever have this memory location and no object in the CPython implementation will ever have an id of zero.

Not sure about other python implementations though

skyking February 2016

Return the “identity” of an object. This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value.

There's nothing that says that it cannot be zero (zero is an integer). If you rely on it not being zero then you're relying on a current implementation detail which is not smart.

What you instead should do is to use for example None to indicate that it isn't an id of an object.

Mike Müller February 2016

If you want an object that is different than any other, you can create one:

special = object()

As long as you don't delete it, special will be unique over the run time of your program. This might achieve the same thing you intend with checking id() being zero.

Post Status

Asked in February 2016
Viewed 2,711 times
Voted 9
Answered 4 times


Leave an answer

Quote of the day: live life