[Tutor] Follow-up Qs: Re: Identity operator (basic types)

Kent Johnson kent37 at tds.net
Sun Feb 11 15:34:20 CET 2007


Cecilia Alm wrote:
> Thanks for the respones. A few follow-up questions:
> 
> For these basic types (float, integer, string, char, bool) does python 
> always figure out the identity change when assigning a 'new value',
> as it seems to do below?
> 
>  >>> i = "hi"
>  >>> j = i
>  >>> print i, j, id(i), id(j)
> hi hi 12235136 12235136
>  >>> j += i
>  >>> print i, j, id(i), id(j)
> hi hihi 12235136 13579872
> 
> In other words, could there ever be a risk of overwriting the original 
> value when copying variables, like i=j?

No.

Did you read the article I pointed to before? Did you "reset your brain" 
as it requests :-) I don't think you understand what Python assignment 
does yet. Python assignment does not copy a value, it creates a new name 
for a value.
> 
> Does one ever have to worry about using copy.deepcopy(i) for these basic 
> types (float, integer, string, char, bool) to avoid overwriting the
> value of the original (like one may have to do for lists and dictionaries?)

No. You can't "overwrite" a value under an circumstances; the concept 
does not make sense in Python.

What you can do is have two names that refer to the same value. If the 
value is mutable, like a list or dict, then changing the value through 
one name will affect the value as seen through the other name. This is 
not overwriting, it is aliasing.

For immutable values you can't change the actual value, you can just 
bind a name to a new value, so the aliasing cannot have unexpected 
side-effects.
> 
> When we copy any such data type (float, integer, string, char, bool) 
> into a function definition's local scope, does it always copy-by-value 
> then? (so one does not have to worry about the original variable's 
> identity and value being changed?)

Again, parameter passing is not copying, it is name-binding. If you pass 
a mutable value to a function and change it in the function, the caller 
will see the change. But name binding inside a function will not affect 
name binding in the caller.

Sorry this is very brief, I don't have time for more explanation. Maybe 
someone else can jump in here.

Kent

> 
>  >>> def sum(k):
>     print k, id(k)
>     k += 1
>     print k, id(k)
> 
>    
>  >>> a = 1234
>  >>> print a, id(a)
> 1234 12536936
>  >>> sum(a)
> 1234 12536936
> 1235 12536876
>  >>> print a, id(a)
> 1234 12536936
> 
> 
> 
> ------------------------------------------------------------------------
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor




More information about the Tutor mailing list