Python dumps core with this.. how come?
Neil Schemenauer
nascheme at enme.ucalgary.ca
Sat Jan 22 15:48:19 EST 2000
Roey Katz <katz at glue.umd.edu> wrote:
>...why does this happen:
>
> >>> a = 3
> >>> b = a
> >>> b
> 3
> >>> a = 5
> >>> b
> 3
Let me try some ASCII art:
a = 3
b = a
gives you this (conceptually):
+---+ +---+
| a |------>| 3 |
+---+ / +---+
/
+---+ /
| b |-/
+---+
When you do:
a = 5
now you have this:
+---+
->| 5 |
/ +---+
/
+---+ / +---+
| a |-/ ->| 3 |
+---+ / +---+
/
+---+ /
| b |-/
+---+
Variables do not contain values. They refer to them. In Python
everything is a reference. Try using the id() function to see
what are the individual objects.
>I mean, what happens if I have a complicated path
>to a variable and I want to alias it:
>
> alias = long_name.hard_to_type[ 1 ].integer_value
>
> # arbitrary calculations that would be
> # torturous with any label longer than 'alias'
> if alias > someValue:
> result = (alias * 5 ) / (alias + 4 )
> else:
> result = (alias * 3 ) / (alias + 2 )
In Python you need one more step:
long_name.hard_to_type[ 1 ].integer_value = alias
When there is a tradoff between convience and explicitness,
Python chooses explicitness. If you have a name that ugly you
are probably doing something wrong already.
>I understand that if I have a function and pass to it a parameter,
>I can modify it in-place (although that I cannot modify numbers,
>strings or tuples in-place seems to me inconsistent).
You can modify objects if they are "mutable". Integers, strings
and tuples are "immutable" for a reason. Just use Python some
more and think about why it is the way it is. The FAQ has some
more details if you are interested.
>So for example, these are roughly equivalent:
>
> void setValue( int& x ) { x = 3 } // C++
> void setValue( int *x ) { *x = 3 } // C
> def setValue( x ): x = 3 # Python
>
>whoops, we cannot modfiy integers in-place, how invonvenient.
Python is not C or C++. You must change your mindset.
>ok, here's a third question, and it builds on the above inquiry
>regarding a lack of an assignment operator. What happens when I want
>to do convert this for loop:
>
> for i,j in dest, src:
> dest[ i ] = src[ j ]
>
>into a fast map() expression:
>
> map( dest.assign_operator, src )
Who says that map() is faster? It certainly is not any more
readable. Why do you want to do such a thing? Premature
optimization is the root of all evil (in programming).
Besides, if you want to copy the sequence why don't you just use
copy.copy()?
>I cannot use filter() to narrow down the list to only the elements
>that I want and then copy it into another list with src.copy().
Sorry, I don't understand what the problem is here:
new_list = filter(my_predicate, my_list)
Why would you want to use copy()? Why do you need an assigment
operator?
Neil
More information about the Python-list
mailing list