Re: Problem with global variables
Anthony Kuhlman [EMAIL PROTECTED] wrote: Pythoners, I'm having trouble understanding the behavior of global variables in a code I'm writing. I have a file, test.py, with the following contents foo = [] def goo(): global foo foo = [] foo.append(2) def moo(): print foo In an ipython session, I see the following: In [1]: from test import * In [2]: foo Out[2]: [] In [3]: goo() In [4]: foo Out[4]: [] In [5]: moo() [2] I don't understand this behavior. I assumed that foo as defined in test.py is a global object, but that doesn't seem to be the case. Obviously, there's some sort of namespace thing going on here that I don't get. The ipython session seems to be dealing with one copy of foo while goo() and moo() are using an entirely different copy. If I take out the line 'foo = []' in goo(), everything behaves exactly as I expect, that is, in ipython, when I type goo() followed by foo I get [2]. Can anyone shed some light on this behavior? The bit of information you need to solve this problem is that python variables are not like variables in other languages, they don't contain values, they refer to them. This means that there can be many names for the same value. You've made two variables called foo, one in the interative interpreter (by your from test import * statement) and one in the test module, and by the time you get to [4] they have different values. The foo in the interpreter still refers to the original list, but the foo in the test module has been overwritten with a new list by the assignment 'foo = []'. This didn't affect the foo in the interactive interpreter. Compare and contrast with this import test test.foo [] test.goo() test.foo [2] test.moo() [2] This works as you expect because you are always using the foo from the test namespace. My advice is to avoid global variables completely. Consider wrapping all your global variables into a class and exporting a single instance of this class to keep your globals in. Eg --- test2.py --- class Test(object): def __init__(self): self.foo = [] def goo(self): self.foo.append(2) def moo(self): print self.foo test = Test() from test2 import test test.foo [] test.goo() test.foo [2] test.moo() [2] -- Nick Craig-Wood [EMAIL PROTECTED] -- http://www.craig-wood.com/nick -- http://mail.python.org/mailman/listinfo/python-list
Problem with global variables
Pythoners, I'm having trouble understanding the behavior of global variables in a code I'm writing. I have a file, test.py, with the following contents foo = [] def goo(): global foo foo = [] foo.append(2) def moo(): print foo In an ipython session, I see the following: In [1]: from test import * In [2]: foo Out[2]: [] In [3]: goo() In [4]: foo Out[4]: [] In [5]: moo() [2] I don't understand this behavior. I assumed that foo as defined in test.py is a global object, but that doesn't seem to be the case. Obviously, there's some sort of namespace thing going on here that I don't get. The ipython session seems to be dealing with one copy of foo while goo() and moo() are using an entirely different copy. If I take out the line 'foo = []' in goo(), everything behaves exactly as I expect, that is, in ipython, when I type goo() followed by foo I get [2]. Can anyone shed some light on this behavior? Cheers, A.J. -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with global variables
On Fri, 08 Aug 2008 13:10:48 -0400, Anthony Kuhlman wrote: I'm having trouble understanding the behavior of global variables in a code I'm writing. I have a file, test.py, with the following contents foo = [] def goo(): global foo foo = [] foo.append(2) def moo(): print foo In an ipython session, I see the following: In [1]: from test import * In [2]: foo Out[2]: [] In [3]: goo() In [4]: foo Out[4]: [] In [5]: moo() [2] I don't understand this behavior. I assumed that foo as defined in test.py is a global object, but that doesn't seem to be the case. ``global`` means module global. There's no really global namespace in Python. The ipython session seems to be dealing with one copy of foo while goo() and moo() are using an entirely different copy. The import binds the list from the module to the name `foo` in the IPython namespace. When you call `goo()` it binds the name `foo` *within the module* to a new list. This has of course no influence on the name in the IPython namespace which is still bound to the list object that was bound to `test.foo` before. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: problem with 'global'
Mel [EMAIL PROTECTED] wrote: oyster wrote: why the following 2 prg give different results? a.py is ok, but b.py is 'undefiend a' I am using Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32 #a.py def run(): if 1==2:# note, it always False global a a=1 run() a #b.py def run(): a=1 run() a The docs seem to be in http://www.python.org/doc/2.4/ref/global.html but don't look all that helpful. Why are you reading Python 2.4 docs? Try http://docs.python.org/ref/global.html The first sentence (which hasn't changed since 2.4) describing the global statement seems clear enough to me: The global statement is a declaration which holds for the entire current code block. -- http://mail.python.org/mailman/listinfo/python-list
Re: problem with 'global'
Duncan Booth wrote: Mel [EMAIL PROTECTED] wrote: oyster wrote: why the following 2 prg give different results? a.py is ok, but b.py is 'undefiend a' I am using Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32 #a.py def run(): if 1==2:# note, it always False global a a=1 run() a #b.py def run(): a=1 run() a The docs seem to be in http://www.python.org/doc/2.4/ref/global.html but don't look all that helpful. Why are you reading Python 2.4 docs? Try http://docs.python.org/ref/global.html The first sentence (which hasn't changed since 2.4) describing the global statement seems clear enough to me: The global statement is a declaration which holds for the entire current code block. I don't think that would stop the OP from thinking the global statement had to be executed. In the code example, it seems to have been stuck in a if 1==2: global a and it still worked. Mel. -- http://mail.python.org/mailman/listinfo/python-list
Re: problem with 'global'
En Mon, 21 Jan 2008 11:44:54 -0200, Mel [EMAIL PROTECTED] escribi�: Duncan Booth wrote: The first sentence (which hasn't changed since 2.4) describing the global statement seems clear enough to me: The global statement is a declaration which holds for the entire current code block. I don't think that would stop the OP from thinking the global statement had to be executed. In the code example, it seems to have been stuck in a if 1==2: global a and it still worked. The future statement is another example, even worse: if 0: from __future__ import with_statement with open(xxx) as f: print f All import statements are executable, only this special form is not. That global and __future__ are directives and not executable statements, is confusing. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: problem with 'global'
On Mon, 21 Jan 2008 17:08:46 -0200, Gabriel Genellina wrote: The future statement is another example, even worse: if 0: from __future__ import with_statement with open(xxx) as f: print f In Python =2.5 it's a compile time error if that import is not the very first statement in a source file. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: problem with 'global'
Marc 'BlackJack' Rintsch [EMAIL PROTECTED] wrote: On Mon, 21 Jan 2008 17:08:46 -0200, Gabriel Genellina wrote: The future statement is another example, even worse: if 0: from __future__ import with_statement with open(xxx) as f: print f In Python =2.5 it's a compile time error if that import is not the very first statement in a source file. That doesn't appear to be the case. With Python 2.5.1 the example Gabriel quoted will compile and run. -- http://mail.python.org/mailman/listinfo/python-list
Re: problem with 'global'
En Mon, 21 Jan 2008 17:36:29 -0200, Duncan Booth [EMAIL PROTECTED] escribi�: Marc 'BlackJack' Rintsch [EMAIL PROTECTED] wrote: On Mon, 21 Jan 2008 17:08:46 -0200, Gabriel Genellina wrote: The future statement is another example, even worse: if 0: from __future__ import with_statement with open(xxx) as f: print f In Python =2.5 it's a compile time error if that import is not the very first statement in a source file. That doesn't appear to be the case. With Python 2.5.1 the example Gabriel quoted will compile and run. Yes, but now I've noticed that the 0 has some magic. The code above works with 0, 0.0, 0j and ''. Using None, False, () or [] as the condition, will trigger the (expected) syntax error. Mmm, it may be the peephole optimizer, eliminating the dead branch. This function has an empty body: def f(): if 0: print 0 if 0.0: print 0.0 if 0j: print 0j if '': print empty py dis.dis(f) 5 0 LOAD_CONST 0 (None) 3 RETURN_VALUE The other false values tested (False, None, () and []) aren't optimized out. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
problem with 'global'
why the following 2 prg give different results? a.py is ok, but b.py is 'undefiend a' I am using Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32 #a.py def run(): if 1==2:# note, it always False global a a=1 run() a #b.py def run(): a=1 run() a -- http://mail.python.org/mailman/listinfo/python-list
Re: problem with 'global'
oyster wrote: why the following 2 prg give different results? a.py is ok, but b.py is 'undefiend a' I am using Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32 #a.py def run(): if 1==2:# note, it always False global a a=1 run() a #b.py def run(): a=1 run() a The docs seem to be in http://www.python.org/doc/2.4/ref/global.html but don't look all that helpful. Probably the key is that global is not an executable statement, and isn't affected by being subordinate to an if statement. In a.py the function has been primed to define a in the global namespace. In b.py, not. Docs do describe global as a directive to the parser, even though it's lumped in with normal statements like print, return, yield, raise, etc. Mel. -- http://mail.python.org/mailman/listinfo/python-list
Re: problem with global var
Bruno Ferreira wrote: I wrote a very simple python program to generate a sorted list of lines from a squid access log file. Now that your immediate problem is solved it's time to look at the heapq module. It solves the problem of finding the N largest items in a list much more efficiently. I think the following does the same as your code: import heapq def key(record): return int(record[4]) logfile = open(squid_access.log, r) records = (line.split() for line in logfile) topsquid = heapq.nlargest(50, records, key=key) for record in topsquid: print record[4] Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: problem with global var
Hello all, Amazing :) The program is working properly now, the code is much better and I learned a bit more Python. Thank you all, guys. Bruno. 2008/1/4, Peter Otten [EMAIL PROTECTED]: Bruno Ferreira wrote: I wrote a very simple python program to generate a sorted list of lines from a squid access log file. Now that your immediate problem is solved it's time to look at the heapq module. It solves the problem of finding the N largest items in a list much more efficiently. I think the following does the same as your code: import heapq def key(record): return int(record[4]) logfile = open(squid_access.log, r) records = (line.split() for line in logfile) topsquid = heapq.nlargest(50, records, key=key) for record in topsquid: print record[4] Peter -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
problem with global var
Hi, I wrote a very simple python program to generate a sorted list of lines from a squid access log file. Here is a simplified version: ## 1 logfile = open (squid_access.log, r) 2 topsquid = [[0, 0, 0, 0, 0, 0, 0]] 3 4 def add_sorted (list): 5 for i in range(50): 6 if int(list[4]) int(topsquid[i][4]): 7 topsquid.insert(i,list) 8 break 8 # Max len = 50 10 if len(topsquid) 50: 11 topsquid = topsquid[0:50] 12 13 while True: 14 logline = logfile.readline() 15 linefields = logline.split() 16 17 if logline != : 18 add_sorted (linefields) 19 else: 20 break 21 22 for i in range (len(topsquid)): 23 print topsquid[i][4] When I execute the program _without_ the lines 10 and 11: 10 if len(topsquid) 50: 11 topsquid = topsquid[0:50] it runs perfectly. But if I execute the program _with_ those lines, this exception is thrown: [EMAIL PROTECTED]:~$ python topsquid.py Traceback (most recent call last): File topsquid.py, line 20, in module add_sorted (linefields) File topsquid.py, line 6, in add_sorted if int(list[4]) int(topsquid[i][4]): UnboundLocalError: local variable 'topsquid' referenced before assignment Note that now the error shown is not related with the lines 10 and 11, but wiht a line prior to them. Any hints? -- Bruno A. C. Ferreira Linux Registered User #181386 -- http://mail.python.org/mailman/listinfo/python-list
Re: problem with global var
Bruno Ferreira wrote: Hi, I wrote a very simple python program to generate a sorted list of lines from a squid access log file. Here is a simplified version: ## 1 logfile = open (squid_access.log, r) 2 topsquid = [[0, 0, 0, 0, 0, 0, 0]] 3 4 def add_sorted (list): Don't call your variable list. There's already the built-in type list. 5 for i in range(50): You should probably use xrange here. 6 if int(list[4]) int(topsquid[i][4]): 7 topsquid.insert(i,list) 8 break 8 # Max len = 50 10 if len(topsquid) 50: 11 topsquid = topsquid[0:50] I'd just use [:50], the 0 is implied. 13 while True: 14 logline = logfile.readline() 15 linefields = logline.split() 16 17 if logline != : 18 add_sorted (linefields) 19 else: 20 break for logline in logfile: if logline: linefields = logline.split() add_sorted(linefields) else: break 22 for i in range (len(topsquid)): 23 print topsquid[i][4] for i in topsquid: print i[4] (You probably want to use a name other than i then.) When I execute the program _without_ the lines 10 and 11: 10 if len(topsquid) 50: 11 topsquid = topsquid[0:50] it runs perfectly. But if I execute the program _with_ those lines, this exception is thrown: [EMAIL PROTECTED]:~$ python topsquid.py Traceback (most recent call last): File topsquid.py, line 20, in module add_sorted (linefields) File topsquid.py, line 6, in add_sorted if int(list[4]) int(topsquid[i][4]): UnboundLocalError: local variable 'topsquid' referenced before assignment Note that now the error shown is not related with the lines 10 and 11, but wiht a line prior to them. Any hints? Basically, you're trying to read the global variable topsquid, and then you're trying to define a local variable topsquid. Python doesn't like that. Declare it as global by adding global topsquid to the top of the function. -- -- http://mail.python.org/mailman/listinfo/python-list
Re: problem with global var
Bruno Ferreira wrote: Hi, I wrote a very simple python program to generate a sorted list of lines from a squid access log file. Here is a simplified version: ## 1 logfile = open (squid_access.log, r) 2 topsquid = [[0, 0, 0, 0, 0, 0, 0]] 3 4 def add_sorted (list): global topsquid 5 for i in range(50): 6 if int(list[4]) int(topsquid[i][4]): 7 topsquid.insert(i,list) 8 break 8 # Max len = 50 10 if len(topsquid) 50: 11 topsquid = topsquid[0:50] 12 13 while True: 14 logline = logfile.readline() 15 linefields = logline.split() 16 17 if logline != : 18 add_sorted (linefields) 19 else: 20 break 21 22 for i in range (len(topsquid)): 23 print topsquid[i][4] When I execute the program _without_ the lines 10 and 11: 10 if len(topsquid) 50: 11 topsquid = topsquid[0:50] it runs perfectly. But if I execute the program _with_ those lines, this exception is thrown: [EMAIL PROTECTED]:~$ python topsquid.py Traceback (most recent call last): File topsquid.py, line 20, in module add_sorted (linefields) File topsquid.py, line 6, in add_sorted if int(list[4]) int(topsquid[i][4]): UnboundLocalError: local variable 'topsquid' referenced before assignment Note that now the error shown is not related with the lines 10 and 11, but wiht a line prior to them. Any hints? Try line 4 add. -- http://mail.python.org/mailman/listinfo/python-list
Re: problem with global var
Bruno Ferreira wrote: Hi, I wrote a very simple python program to generate a sorted list of lines from a squid access log file. Here is a simplified version: ## 1 logfile = open (squid_access.log, r) 2 topsquid = [[0, 0, 0, 0, 0, 0, 0]] 3 4 def add_sorted (list): 5 for i in range(50): 6 if int(list[4]) int(topsquid[i][4]): 7 topsquid.insert(i,list) 8 break 8 # Max len = 50 10 if len(topsquid) 50: 11 topsquid = topsquid[0:50] 12 13 while True: 14 logline = logfile.readline() 15 linefields = logline.split() 16 17 if logline != : 18 add_sorted (linefields) 19 else: 20 break 21 22 for i in range (len(topsquid)): 23 print topsquid[i][4] When I execute the program _without_ the lines 10 and 11: 10 if len(topsquid) 50: 11 topsquid = topsquid[0:50] it runs perfectly. But if I execute the program _with_ those lines, this exception is thrown: [EMAIL PROTECTED]:~$ python topsquid.py Traceback (most recent call last): File topsquid.py, line 20, in module add_sorted (linefields) File topsquid.py, line 6, in add_sorted if int(list[4]) int(topsquid[i][4]): UnboundLocalError: local variable 'topsquid' referenced before assignment Note that now the error shown is not related with the lines 10 and 11, but wiht a line prior to them. Any hints? Use def add_sorted(list): global topsquid ... to make topsquid a global variable to add_sorted. Otherwise python sees that it gets referred by in the if-statement before assigning to it, thus resulting in the error you see. The reason for this is that a (limited) static analysis of python-code is performed to determine which variables are local to a function and which not. The criteria essentially is the appearance on the left-hand-side of an expression makes a variable (or name) local to that function. Which makes it require the explicit global declaration. Apart from that there are quite a few things worth mentioning in your code: - don't shadow built-in names like list - it's superfluous to do for i in xrange(len(some_list)): .. some_list[i] .. as you do, unless you need the index. Instead do for element in some_list: ... element ... If you need an index, do for i, element in enumerate(some_list): ... - don't use range, use xrange if you don't need a list but rather want to enumerate indices. - the while-loop is superfluous as well, just do for line in logfile: ... or if your python is older do for line in logfile.xreadlines(): ... Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: problem with global var
Bruno Ferreira wrote: When I execute the program _without_ the lines 10 and 11: 10 if len(topsquid) 50: 11 topsquid = topsquid[0:50] it runs perfectly. But if I execute the program _with_ those lines, this exception is thrown: [EMAIL PROTECTED]:~$ python topsquid.py Traceback (most recent call last): File topsquid.py, line 20, in module add_sorted (linefields) File topsquid.py, line 6, in add_sorted if int(list[4]) int(topsquid[i][4]): UnboundLocalError: local variable 'topsquid' referenced before assignment Python uses static analysis to determine if a variable is local to a function; somewhat simplified, if you assign to the variable inside the function, *all* uses of that variable inside the function will be considered local. for the full story, see: http://docs.python.org/ref/naming.html to fix this, you can insert a global declaration at the top of the def add_sorted (list): global topsquid # mark topsquid as global in this function ... in this case, you can also avoid the local assignment by modifying the list in place; if len(topsquid) 50: topsquid[:] = topsquid[0:50] or, as a one-liner: del topsquid[50:] /F -- http://mail.python.org/mailman/listinfo/python-list
Re: problem with global var
On Thu, 03 Jan 2008 11:38:48 -0300, Bruno Ferreira wrote: Hi, I wrote a very simple python program to generate a sorted list of lines from a squid access log file. Here is a simplified version: ## 1 logfile = open (squid_access.log, r) 2 topsquid = [[0, 0, 0, 0, 0, 0, 0]] [snip] Others have already solved the immediate problem, but a much better design would be to avoid using a global variable in the first place. def add_sorted(alist, data): Add figures from alist to collated data and return data. # do your processing here... return data topsquid=[[0, 0, 0, 0, 0, 0, 0]] for line in logfile: linefields = logline.split() topsquid = add_sorted(linefields, topsquid) -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Problem with global
Hello, I have a little problem with the global statement. def executeSQL(sql, *args): try: import pdb; pdb.set_trace() cursor = db.cursor() # db is type 'NoneType'. [...] except: print Problem contacting MySQL database. Please contact root. sys.exit(-1) db = None # Global Variable for DB connection def main(): [...] global db db = MySQLdb.connect(...) [...] executeSQL(sql, args) Why isn't the global variable db not written in main() to be a mysql connection and still none type in executeSQL? Thanks, Florian -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with global
Florian Lindner wrote: Hello, I have a little problem with the global statement. def executeSQL(sql, *args): try: import pdb; pdb.set_trace() cursor = db.cursor() # db is type 'NoneType'. [...] except: print Problem contacting MySQL database. Please contact root. sys.exit(-1) db = None # Global Variable for DB connection def main(): [...] global db db = MySQLdb.connect(...) [...] executeSQL(sql, args) Why isn't the global variable db not written in main() to be a mysql connection and still none type in executeSQL? Thanks, Florian Because you have it to let executeSQL know that it is global or it creates a local copy in local namespace. def executeSQL(sql, *args): global db try: import pdb; pdb.set_trace() cursor = db.cursor() # db is type 'NoneType'. [...] except: print Problem contacting MySQL database. Please contact root. sys.exit(-1) -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with global
Larry Bates wrote: Florian Lindner wrote: Hello, I have a little problem with the global statement. def executeSQL(sql, *args): try: import pdb; pdb.set_trace() cursor = db.cursor() # db is type 'NoneType'. [...] except: print Problem contacting MySQL database. Please contact root. sys.exit(-1) db = None # Global Variable for DB connection def main(): [...] global db db = MySQLdb.connect(...) [...] executeSQL(sql, args) Why isn't the global variable db not written in main() to be a mysql connection and still none type in executeSQL? Thanks, Florian Because you have it to let executeSQL know that it is global or it creates a local copy in local namespace. That's not right in the context because db is read before it written. Therefore the global copy springs into the local namespace. def executeSQL(sql, *args): global db try: import pdb; pdb.set_trace() cursor = db.cursor() # db is type 'NoneType'. [...] except: print Problem contacting MySQL database. Please contact root. sys.exit(-1) I've solved it. It was a problem you could not have possibly seen. Actually in my script executeSQL is called before db = MySQLdb.connect(..) is called. When I have simplified the code for the posting I've changed it made it right without knowing. Regards, Florian -- http://mail.python.org/mailman/listinfo/python-list
Problem with global variables
I'm having a vexing problem with global variables in Python. Please consider the following Python code: #! /usr/bin/env python def tiny(): bar = [] for tmp in foo: bar.append(tmp) foo = bar if __name__ == __main__: foo = ['hello', 'world'] tiny() When I try to run this, I get: Traceback (most recent call last): File ./xtalk.py, line 11, in ? tiny() File ./xtalk.py, line 5, in tiny for tmp in foo: UnboundLocalError: local variable 'foo' referenced before assignment For some reason, Python can't see the global variable foo in the function tiny(). Why is that? If I change the code to this: #! /usr/bin/env python def tiny(): for tmp in foo: print tmp if __name__ == __main__: foo = ['hello', 'world'] tiny() I get this: hello world All of a sudden, tiny() can see the global variable foo. Very confusing! Why is it that tiny() sometimes can, and sometimes can't, see the global variable foo? If anyone can enlighten me about what's going on with Python and global variables, I would appreciate it! -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with global variables
Ed Jensen wrote: #! /usr/bin/env python def tiny(): bar = [] for tmp in foo: bar.append(tmp) foo = bar if __name__ == __main__: foo = ['hello', 'world'] tiny() Like this ? #! /usr/bin/env python def tiny(): bar = [] gobal foo for tmp in foo: bar.append(tmp) foo = bar if __name__ == __main__: foo = ['hello', 'world'] tiny() hg -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with global variables
Ed Jensen a écrit : I'm having a vexing problem with global variables in Python. Please consider the following Python code: #! /usr/bin/env python def tiny(): bar = [] for tmp in foo: bar.append(tmp) foo = bar if __name__ == __main__: foo = ['hello', 'world'] tiny() When I try to run this, I get: Traceback (most recent call last): File ./xtalk.py, line 11, in ? tiny() File ./xtalk.py, line 5, in tiny for tmp in foo: UnboundLocalError: local variable 'foo' referenced before assignment For some reason, Python can't see the global variable foo in the function tiny(). Why is that? If I change the code to this: #! /usr/bin/env python def tiny(): for tmp in foo: print tmp if __name__ == __main__: foo = ['hello', 'world'] tiny() I get this: hello world All of a sudden, tiny() can see the global variable foo. Very confusing! Why is it that tiny() sometimes can, and sometimes can't, see the global variable foo? If anyone can enlighten me about what's going on with Python and global variables, I would appreciate it! To complete hg reply, Python compile your tiny function which contains a foo assignment. As foo is not defined global, it is considered to be local. So the error when you tries to iterate throught foo before assigning it. And so the solution to add global foo before using it. A+ Laurent. -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with global variables
Laurent Pointal wrote: And so the solution to add global foo before using it. Didn't you read his final question? | All of a sudden, tiny() can see the global variable foo. Very | confusing! Why is it that tiny() sometimes can, and sometimes | can't, see the global variable foo? I have no explanation for this, but I'm interested in one, too. Regards, Björn -- BOFH excuse #422: Someone else stole your IP address, call the Internet detectives! -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with global variables
Bjoern Schliessmann wrote: Laurent Pointal wrote: And so the solution to add global foo before using it. Didn't you read his final question? | All of a sudden, tiny() can see the global variable foo. Very | confusing! Why is it that tiny() sometimes can, and sometimes | can't, see the global variable foo? I have no explanation for this, but I'm interested in one, too. It doesn't happen all of a sudden, it happens when the assignment to foo is removed from the function definition. The interpreter therefore no longer regards foo as a local variable. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with global variables
Bjoern Schliessmann schreef: Laurent Pointal wrote: And so the solution to add global foo before using it. Didn't you read his final question? | All of a sudden, tiny() can see the global variable foo. Very | confusing! Why is it that tiny() sometimes can, and sometimes | can't, see the global variable foo? I have no explanation for this, but I'm interested in one, too. Within functions Python can read from global variables, even without a 'global' statement. Complications only arise when you try to write to it: in that case Python assumes it is a local variable instead of a global. It surprised me a bit when I first found out about this: I would have thought that Python would threat it as a local throughout the function until the function assigns something to it. That's not what happens: if the function assigns to it, *all* mentions of the variable are considered local. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with global variables
On Apr 2, 5:29 pm, Bjoern Schliessmann usenet- [EMAIL PROTECTED] wrote: Laurent Pointal wrote: And so the solution to add global foo before using it. Didn't you read his final question? | All of a sudden, tiny() can see the global variable foo. Very | confusing! Why is it that tiny() sometimes can, and sometimes | can't, see the global variable foo? I have no explanation for this, but I'm interested in one, too. Regards, Björn Laurent Pointal did explain this. foo is considered to be a local variable (scope limited to the function) if it's being assigned to in a function and there's no global foo statement. So even the foo before the actual assignment will refer to the local variable. But the local variable hasn't been assigned yet at that point and an exception is thrown. Yes, one could have a perfectly working function, then add an innocent-looking assignment statement at the very end of the function, and suddenly you'd get an exception thrown at the beginning of the function where that variable is used - Far away from the place where the modification was made. Why does it work like this? Couldn't it be somehow more uniform or less surprising? Well, if one had to define global foo even when one were to just read the variable foo, that'd be a pain in the ass. You'd have to use global math to use math module in a function and global anotherFunction to call anotherFunction, and so on. There's plenty of stuff in the global scope that you don't normally assign to. Another option would be to scrap global keyword and let foo = bar do an assignment to the global variable if a global variable named foo exists, but create (or assign) to a function local variable if it doesn't exist. That'd work but programming would be horrible. Now you'd have to know all the symbols that exist at the global scope, because if you accidentally accessed a global variable instead of local, your function would probably have undesirable side-effects. Now, name clashes could be solved with a naming convention (which could be enforced at the language level). It could be possible that all accesses to global scope would have to be prefixed by some symbol like $. E.g. $foo = 4; foo = 6 where former assigns to global foo, latter to local foo. That's one option that might work and be somewhat readable.. But not a good tradeoff IMO, considering how rarely global assignment is needed and how often global variables are read. A remaining option is to use different operator for assignment and initialization. So you'd have to do e.g. a := 4; a = 7. I'm not sure Pythonistas would prefer this either, although many other languages choose this route (through lets or declarations typically). -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with global variables
Ed Jensen [EMAIL PROTECTED] wrote: I'm having a vexing problem with global variables in Python. SNIP Thanks to everyone who replied. The peculiar way Python handles global variables in functions now makes sense to me. -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with global variables
Bjoern Schliessmann wrote: Laurent Pointal wrote: And so the solution to add global foo before using it. Didn't you read his final question? Yes, and i replies: which contains a foo assignment. As foo is not defined global, it is considered to be local. Maybe my explanation was not clear enough with variable foo to be considered local because there is an *assignment* to foo. A+ Laurent. -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with global variables
Laurent Pointal wrote: Yes, and i replies: which contains a foo assignment. As foo is not defined global, it is considered to be local. Maybe my explanation was not clear enough with variable foo to be considered local because there is an *assignment* to foo. Yep, thanks for the clarification. After four replies and despite weird conjugations, I've definitely got it now ... ;) Regards, Björn -- BOFH excuse #113: Root nameservers are out of sync -- http://mail.python.org/mailman/listinfo/python-list
problem with global variable in a module
def aa(): global b b=b+1 print b b=1 aa() The above code runs well in python shell. However I have a problem as follows. new a file named test.py def aa(): global b b=b+1 print b - Then in python shell, from test import * b=1 aa() The error message is : Traceback (most recent call last): File interactive input, line 1, in ? File test.py, line 3, in aa b=b+1 NameError: global name 'b' is not defined Why this happens? Please do me a favor. Thanks in advance -- http://mail.python.org/mailman/listinfo/python-list
Re: problem with global variable in a module
hollowspook [EMAIL PROTECTED] wrote: from test import * b=1 aa() The error message is : Traceback (most recent call last): File interactive input, line 1, in ? File test.py, line 3, in aa b=b+1 NameError: global name 'b' is not defined Why this happens? Please do me a favor. The global statement makes a name global to a module, it doesn't make it global to the entire program. The function aa is in module test, the statements you entered in the shell are in a different module called __main__. The particular form of import you used may also be confusing you: just because you imported '*' doesn't change the function: 'aa' was defined in the module 'test' and that is where it still looks for its global variables, all the import did was define a new name 'aa' in the __main__ module which refers to the same function object as 'aa' in 'test'. -- http://mail.python.org/mailman/listinfo/python-list
Re: problem with global variable in a module
hollowspook schrieb: def aa(): global b b=b+1 print b b=1 aa() The above code runs well in python shell. However I have a problem as follows. new a file named test.py def aa(): global b b=b+1 print b - Then in python shell, from test import * b=1 aa() The error message is : Traceback (most recent call last): File interactive input, line 1, in ? File test.py, line 3, in aa b=b+1 NameError: global name 'b' is not defined Why this happens? Please do me a favor. Because python does not know real globals - globals are always only global on a module level. Now using the from module import *-syntax asks for trouble. Because your global b above is global to the __main__-module, not to the module test. But the aa-function expects it to live in tests. To make your example work, do it as this: import test test.b = 1 test.aa() See http://effbot.org/pyfaq/tutor-whats-the-difference-between-import-foo-and-from-foo-import.htm Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: problem with global variable in a module
Thanks for all the replys. Diez B. Roggisch 写道: hollowspook schrieb: def aa(): global b b=b+1 print b b=1 aa() The above code runs well in python shell. However I have a problem as follows. new a file named test.py def aa(): global b b=b+1 print b - Then in python shell, from test import * b=1 aa() The error message is : Traceback (most recent call last): File interactive input, line 1, in ? File test.py, line 3, in aa b=b+1 NameError: global name 'b' is not defined Why this happens? Please do me a favor. Because python does not know real globals - globals are always only global on a module level. Now using the from module import *-syntax asks for trouble. Because your global b above is global to the __main__-module, not to the module test. But the aa-function expects it to live in tests. To make your example work, do it as this: import test test.b = 1 test.aa() See http://effbot.org/pyfaq/tutor-whats-the-difference-between-import-foo-and-from-foo-import.htm Diez -- http://mail.python.org/mailman/listinfo/python-list