Object identity (was: Reference)

Ben Finney ben+python at benfinney.id.au
Mon Mar 3 05:00:18 EST 2014


"ast" <nomail at invalid.com> writes:

> >>> A=7
> >>> B=7
> >>> A is B
> True
>
> I understand that there is a single object 7 somewhere in memory and
> both variables A and B point toward this object 7

Try not to think in terms of “point to”. Rather, the names “A” and “B”
are bound to that object.

The distinction is subtle; but it's important to realise that *all*
references in Python do this, and there's no way to talk about an object
in Python without using a reference. The “pointer” model from other
languages doesn't exist in Python.

> now do the same with a list:
>
> >>> l1 = [1, 2]
> >>> l2 = [1, 2]
> >>> l1 is l2
> False
>
> It seems this time that there are 2 distincts objects [1, 2] in
> memory.

That's correct.

> I dont really understand why the behavior is different. Both integer 7
> and list [1, 2] are objects. Why is it different ?

Short answer: object identity is an implementation detail.

It's up to the Python implementation to decide when to re-use an object
when a new one is requested. No guarantee is made, when you ask to
create an object, that you won't get an existing one if that would work
just as well.

Since the integer object 7 is immutable, it will behave the same no
matter how many times you ask for a new one, the Python implementation
can choose to give you the same object. But it might not — don't depend
on this!

Since two separate lists are mutable, each one can have a distinct
history after creation, so it would be less helpful to return an
existing list when you ask for a new one. But again, there's no
guarantee here either! A Python implementation might decide to give you
an existing list, if existing guarantees can be kept.

The moral is: Don't depend on differences in object identity. You can be
guaranteed that an object will retain its own identity, and its identity
will always be different from all other co-existing objects that have
different values. Beyond that, don't make any assumptions.

-- 
 \              “Programs must be written for people to read, and only |
  `\        incidentally for machines to execute.” —Abelson & Sussman, |
_o__)              _Structure and Interpretation of Computer Programs_ |
Ben Finney




More information about the Python-list mailing list