global and None
Francis Avila
francisgavila at yahoo.com
Tue Dec 23 04:48:43 EST 2003
Leo Yee wrote in message ...
>My purpose is to init g. This is very useful when we cannot construct a
>global variable.
Like when? And why?
>But what I got was:
>UnboundLocalError: local variable 'g' referenced before assignment
Yes; the Python bytecode compiler assumes g is a local unless you specify
otherwise (with the global statement). So when g is referenced, it doesn't
yet exist in the local namespace, even though Python looks for it there.
Hence the error.
Your first global is redundant, because you're already in the global
namespace.
>So I try to solve the problem in this way:
>--- code begin ---
>
>global g
>g=None
>def foo():
> global g
> if g==None:
> g=0
>foo()
>
>--- code end ---
>
>And it works but the python documentation told me the following:
>"Names listed in a global statement must not be defined as formal
parameters
>or in a for loop control target, class definition, function definition, or
>import statement. "
Actually, I've looked at this closely, and thought about it a bit, and I'm
not sure I understand what the docs mean. Here are my guesses:
"formal parameters"
def foo(a=1):
global a
SyntaxError: name 'a' is local and global ("<stdin>", line ?)
Ok, no doubt there.
...
"for loop control target" I believe means you can't do the following:
def foo():
global i
for i in range(10):
pass
However, you *can* do it, and section 6.3 (assignment statements), where
target_list semantics are expounded, allows it:
"""
Assignment of an object to a single target is recursively defined as
follows.
- If the target is an identifier (name):
+ If the name does not occur in a global statement in the current code
block: the name is bound to the object in the current local namespace.
+ Otherwise: the name is bound to the object in the current global
namespace.
"""
Python bug or doc bug in "global"? Or do I misunderstand?
...
moving on: "class definition, function definition"
def bar():
global foo
class/def foo(object):
pass
???
This is currently legal, and works AFAICT. Why should it be prohibited,
aside from being dangerous and abusive?
...
"import statement"
Same thing:
def foo():
global re
import re
foo() # imports re globally.
Currently possible, ugly, and dangerous, but prohibited?
>Does anyone know what I should do to solve this problem? Thanks in advance.
What problem? The way you use global doesn't fall under any of these cases
it prohibits. Aside from that, all the cases it prohibits work just fine.
BTW, your code should be:
g = None
def foo():
global g
if g == None:
g = 0
Notice, no 'global g' at the top.
This is why global was made, you know. You're using it properly. Whether
you should be using globals, however, is another story ;)
--
Francis Avila
More information about the Python-list
mailing list