python assignment

Terry Reedy tjreedy at
Wed Jul 23 04:26:51 CEST 2003

"dan" <danbmil99 at> wrote in message
news:fbf8d8f2.0307221659.1dd1ac77 at
> without stirring the pot too much --
> could someone please point me to whatever documentation exists on
> philosophy, semantics, and practical implications of how Python
> implements the assignment operator?

Go to and search their for 'assignment' during the
last 6 months.

>  I understand the basic concept that
> names are bound to objects which exist on the heap, but that still
> doesn't explain why a = b doesn't _always_ cause a to point to the
> same object as b.

But is *does*!!!

> What determines when the object in question is copied?

The programmer, by explicitly coding a copy operation.  Assignment
*never*, that I can think of, creates a new object by itself.  Name =
object *always* binds name to object in the appropriate namespace.

> What I need is an exact and unambiguous algorithm for determining
> an assignment will change the id of the variable

Variables do not have ids, only Pyobjects.

>(or should I say,  when the evaluation of an expression will cause
> a new object to be created).

Entirely separate issue.  Names in expressions always evaluate to an
existing object.  Attributes and collection item retrievals usually
do.  Non-method operations usually do not.

>  Some of the issues involved can be discerned from the following

I am beginning to think that Python newbies should not be told about
id() and 'is' until they have learned enough to not misinterpret the

> >>> a = 1
> >>> b = a
> >>> a is b
> True

Correct, for the reason you think.

> >>> a += 1
> >>> a -= 1
> >>> a is b
> True

Correct, but probably not why you think.  For immutable types, two
copies are the same as one copy, so the interpreter free to reuse an
existing object of the same value as needed rather than allocate a
redundant duplicate.  CPython does this for commonly used small ints,

>>> import sys
>>> sys.getrefcount(1)
50 #49 internal, 1 from the function call

but this is an implementation detail newbies should not worry about
(except out of idle curiosity -- which I had also ;-).  If you really
are curious, repeat the above with -2, -1, 99, 100, 101.  Also,
experiment with 'a', 'aa', and 'a a'.

> >>> a = 1.0
> >>> b = a
> >>> a is b
> True

Same as example one.

> >>> a += 1
> >>> a -= 1
> >>> a is b
> False

Correct, CPython does not preallocate any floats.

> >>> a == b
> True

Numbers compare by numerical value, independent of type:
>>> 0 == 0L == 0.0 == 0.0+0.0j

Terry J. Reedy

More information about the Python-list mailing list