kelvinsong
kelvinsong

Reputation: 218

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.

Upvotes: 0

Views: 204

Answers (4)

Mike Müller
Mike Müller

Reputation: 85522

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.

Upvotes: 0

skyking
skyking

Reputation: 14400

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.

Upvotes: 4

Wombatz
Wombatz

Reputation: 5458

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

Upvotes: 6

Foon
Foon

Reputation: 6468

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.

Upvotes: 0

Related Questions