Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python atomic data types

It was written here that Python has both atomic and reference object types. Atomic objects are: int, long, complex. When assigning atomic object, it's value is copied, when assigning reference object it's reference is copied.

My question is: why then, when i do the code bellow i get 'True'?

a = 1234
b = a
print id(a) == id(b)

It seems to me that i don't copy value, i just copy reference, no matter what type it is.

like image 235
Artem Sliusar Avatar asked Aug 24 '16 14:08

Artem Sliusar


1 Answers

Assignment (binding) in Python NEVER copies data. It ALWAYS copies a reference to the value being bound.

The interpreter computes the value on the right-hand side, and the left-hand side is bound to the new value by referencing it. If expression on the right-hand side is an existing value (in other words, if no operators are required to compute its value) then the left-hand side will be a reference to the same object.

After

a = b

is executed,

a is b

will ALWAYS be true - that's how assignment works in Python. It's also true for containers, so x[i].some_attribute = y will make x[i].some_attribute is y true.

The assertion that Python has atomic types and reference types seems unhelpful to me, if not just plain untrue. I'd say it has atomic types and container types. Containers are things like lists, tuples, dicts, and instances with private attributes (to a first approximation).

As @BallPointPen helpfully pointed out in their comment, mutable values can be altered without needing to re-bind the reference. Since immutable values cannot be altered, references must be re-bound in order to refer to a different value.

Edit: Recently reading the English version of the quoted page (I'm afraid I don't understand Russian) I see "Python uses dynamic typing, and a combination of reference counting and a cycle-detecting garbage collector for memory management." It's possible the Russian page has mistranslated this to give a false impression of the language, or that it was misunderstood by the OP. But Python doesn't have "reference types" except in the most particular sense for weakrefs and similar constructs.

like image 198
holdenweb Avatar answered Oct 11 '22 03:10

holdenweb