Re: Curious UnboundLocalError Behavior



I'm probably fundamentally misunderstanding the way the interpreter
works with regard to scope, but is this the intended behavior...


[....]

SOMEGLOBAL:
Traceback (most recent call last):
File "unboundlocal.py", line 15, in ?
foo()
File "unboundlocal.py", line 11, in foo
print "SOMEGLOBAL:",SOMEGLOBAL
UnboundLocalError: local variable 'SOMEGLOBAL' referenced before assignment

[......]

import os,sys

SOMEGLOBAL=1

def foo():
dome=False
if dome:
SOMEGLOBAL = 0

print globals()
print "SOMEGLOBAL:",SOMEGLOBAL

print os.uname()
print sys.version
foo()



Try:

import os,sys

SOMEGLOBAL=1

def foo():
global SOMEGLOBAL
dome=False
if dome:
SOMEGLOBAL = 0

print globals()
print "SOMEGLOBAL:",SOMEGLOBAL

print os.uname()
print sys.version
foo()

HTH,
Daniel
.



Relevant Pages

  • Re: Scope
    ... > def main: ... > if foo needs to take different arguments, ... > foo, globals()) ... they can be just aliases to Python's VM bytecodes ...
    (comp.lang.python)
  • Re: defvar affecting captured closure variables ?
    ... ignore the advice about global lexicals. ... | bind these globals, since otherwise you'll get a lexical foo when you ... | bind foo. ... again distracting as ar esult). ...
    (comp.lang.lisp)
  • using "our" across blocks
    ... I want to double-check that it is correct to use "our" to import globals. ... our $foo = 'foo'; ... ...at this point I can see 'foo' and 'bar' values. ... Global symbol "$foo" requires explicit package name at ./script.pl line xx. ...
    (perl.beginners)
  • Re: namespaces and eval
    ... Def foo: ... and globals will pull in anything in module X. ... that's kind of a hack already ... compose(foo, foo, foo, foo) ...
    (comp.lang.python)
  • Re: Rebindings [was Re: Favorite non-python language trick?]
    ... oops, for below example, needs global declaration ... def foo(): ... So that limits it to the local scope and nested scopes and declared globals not ... preempted by nearer nested scope variable names. ...
    (comp.lang.python)