473,467 Members | 1,585 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

lists: += vs. .append() & oddness with scope of variables

I'd like to understand why += operator raises an error while .append() does
not. My wild guess is the parses treats them differently but I cannot
understand why this depends on scope of the variables (global or class
variables):
a = [0]

class foo(object):

def __init__(self):
print "a: ", a
# += does not work if 'a' is global
#a += [1]
a.append(2)
print "a= ", a

class bar(object):

b = [0]

def __init__(self):
print "b: ", self.b
# += *does* work if 'a' is class var
self.b += [1]
self.b.append(2)
print "b= ", self.b
if __name__ == '__main__':
x = foo()
y = bar()

a: [0]
a= [0, 2]
b: [0]
b= [0, 1, 2]

uncommenting 'a += [1]' would raise:

a:
Traceback (most recent call last):
File "c1.py", line 26, in ?
x = foo()
File "c1.py", line 7, in __init__
print "a: ", a
UnboundLocalError: local variable 'a' referenced before assignment

TIA
sandro
*:-)
--
Sandro Dentella *:-)
e-mail: sa****@e-den.it
http://www.tksql.org TkSQL Home page - My GPL work
Mar 5 '06 #1
4 1275
Em Dom, 2006-03-05 Ã*s 11:49 +0000, Sandro Dentella escreveu:
class foo(object):

def __init__(self):
print "a: ", a
# += does not work if 'a' is global
#a += [1]
a.append(2)
print "a= ", a


Try with:
a = [0]

class foo(object):
def __init__(self):
global a
print "a: ", a
a += [1]
a.append(2)
print "a= ", a

foo()

--
"Quem excele em empregar a força militar subjulga os exércitos dos
outros povos sem travar batalha, toma cidades fortificadas dos outros
povos sem as atacar e destrói os estados dos outros povos sem lutas
prolongadas. Deve lutar sob o Céu com o propósito primordial da
'preservação'. Desse modo suas armas não se embotarão, e os ganhos
poderão ser preservados. Essa é a estratégia para planejar ofensivas."

-- Sun Tzu, em "A arte da guerra"

Mar 5 '06 #2
Sandro Dentella wrote:
I'd like to understand why += operator raises an error while .append()
does not. My wild guess is the parses treats them differently but I
cannot understand why this depends on scope of the variables (global
or class variables):
a = [0]

class foo(object):

def __init__(self):
print "a: ", a
# += does not work if 'a' is global
#a += [1]
a.append(2)
print "a= ", a


Any assignment to a variable within a function means that the name to which
you are assigning is regarded as a local variable (unless you use the
'global' statement to override that). += is a form of assignment, calling
the append method is not an assignment.

The solution here is simply to use 'global a' to tell the compiler that you
meant to assign the the global variable rather than creating a new local
variable.
Mar 5 '06 #3
Duncan Booth wrote:
Sandro Dentella wrote:
I'd like to understand why += operator raises an error while .append()
does not. My wild guess is the parses treats them differently but I
cannot understand why this depends on scope of the variables (global
or class variables):

....

Any assignment to a variable within a function means that the name to which
you are assigning is regarded as a local variable (unless you use the
'global' statement to override that). += is a form of assignment, calling
the append method is not an assignment.

The solution here is simply to use 'global a' to tell the compiler that you
meant to assign the the global variable rather than creating a new local
variable.


As Duncan knows but forgot to mention, eric.append(spam) doesn't write
the variable eric, it simply manipulates the object that eric names.

--
-Scott David Daniels
sc***********@acm.org
Mar 5 '06 #4

"Sandro Dentella" <sa****@e-den.it> wrote in message
news:sl*******************@bluff.diade.it...
I'd like to understand why += operator raises an error while .append()
does
not.
Your mistake is thinking of '+=' as an operator. In Python terms it is
not, any more than '=' is. In Python, neither 'a=b' nor 'a+=b' is an
expression. Both symbols are statement symbols that define assigment
statements (augmented in the former case). "a.append(b)" is an expression
with side effects used as a statement.
Traceback (most recent call last):
File "c1.py", line 26, in ?
x = foo()
File "c1.py", line 7, in __init__
print "a: ", a
UnboundLocalError: local variable 'a' referenced before assignment


This is the clue that you did not get. It tells you that the parser thinks
'a' is local, which means you rebound the name 'a' *somewhere* in the
function, even if not as obviously as a simple assignment "a = whatever".
It turns out that augmented assignment statements are assignments
statements ;-).

Terry Jan Reedy

Mar 5 '06 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
by: Klaus Neuner | last post by:
Hello, I would like to understand the reason for the following difference between dealing with lists and dealing with strings: What is this difference good for? How it is accounted for in Python...
3
by: flamesrock | last post by:
Lets say I have a list containing 12, 13, 23 or however many entries. What I want is the greatest number of lists evenly divisible by a certain number, and for those lists to be assigned to...
5
by: Jan Danielsson | last post by:
Hello all, I have written a simple whiteboard application. In my application, I want to be able to set draw attributes. This part works. I have a dictionary object which contains stuff like:...
4
by: yaffa | last post by:
dear folks, i'm trying to append a semicolon to my addr string and am using the syntax below. for some reason the added on of the ; doesn't work. when i print it out later on it only shows the...
9
by: vp | last post by:
Can I safely assume that all static variables are initialized as NULL or zero, depending on the types of the variables, no matter on which platform that app is compiled ? Thanks for your help, ...
2
by: Estella | last post by:
Hello, I wrote a function called eat_path() to split a string into components e.g. /a/b/c ==> namePtr = a,namePtr = a, namePtr = c // Global variable char *namePtr = {0}; int n; /*number of...
14
by: G Patel | last post by:
Pg. 140 of K&R2 shows an example of mutually referential structure declarations... struct t { struct s *p; }; struct s {
11
by: rshepard | last post by:
I start with a list of tuples retrieved from a database table. These tuples are extracted and put into individual lists. So I have lists that look like this: . When I concatenate lists, I end up...
1
pbmods
by: pbmods | last post by:
VARIABLE SCOPE IN JAVASCRIPT LEVEL: BEGINNER/INTERMEDIATE (INTERMEDIATE STUFF IN ) PREREQS: VARIABLES First off, what the heck is 'scope' (the kind that doesn't help kill the germs that cause...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.