Newbie question
Ante
abagaric at rest-art.hr
Wed Apr 17 03:45:43 EDT 2002
"Paul Osman" <paul.osman at sympatico.ca> wrote in message
news:mailman.1018979135.19771.python-list at python.org...
> Okay, let me try this again... Python detects local names statically.
> Variables assigned in a function are classified as local by default.
> therefore in the following script:
>
> This is because there are actually two variables named "num", one
> global, and one local to the function dummy(). Now, if we were to do
> take out the assignment from the dummy() function, the output would be:
I am new to Python, but I'm not quite new to programming in general...
I see what you are saying, no need to use the syntax as you would with a
total programming newbie. :) I mean, I know what global and local means,
and I know 'global num' would solve the problem. But that was not the issue.
Let me try another example:
dummy.py:
--------------------------------
num = [1]
def dummy():
num.append(2)
print num
dummy()
------------------------------
>>> import dummy
[1, 2]
See? I was changing the list, and yet it didn't produce an error.
But, if I used
num += [2]
instead of
num.append(2)
it would again produce an exception.
Now. don't those two expressions mean the same? I am not changing
the reference, (as I would if I used plain =) but I am rather modifying the
list itself, without moving the reference. Here is the proof:
>>> li = [1,2,3]
>>> li2 = li
>>> li += [2]
>>> li is li2
1
So, the li reference hasn't moved after I used += operator. Wouldn't be true
if I used operator =.
So, the question was: while it made some sense that if I used the operator =
the compiler would assume it is a new, local name, it doesn't make as much
sense to assume the same thing if I used +=. Because, in order to
'increment'
something, I already need its initial value. But, if you still think any
changes to
a name should make the compiler assume it's local, then num.append() should
assume it just as well. Am I not right?
Ante
More information about the Python-list
mailing list