Sunday, 15 May 2011

scope - Python: global name 'foobar' is not defined -



scope - Python: global name 'foobar' is not defined -

can explain why next code produces error "global name 'foobar' not defined" on line 12 (the print statement)? thought understood scope in python, giving me fits.

def main(): # initialize global foobar foobar = foo() class foo(): def __init__(self): self.bar = bar() class bar(): def __init__(self): print foobar #call main() when script executed if __name__ == '__main__': main()

at time foo() called, foobar not yet defined (it won't until foo() returns , homecoming value assigned foobar. however, foobar accessed by phone call foo(), indirectly vi phone call bar.__init__(). thus, @ time print foobar in bar.__init__ executed, global foobar not yet defined. if set value of foobar prior phone call main, you'll see value printed before foo object assigned. seek following

if __name__ == "__main__": foobar = 3 foobar = foo() # output "3" print foobar # print <__main__.foo object @ 0x.....>

as abarnert points out, global foobar doesn't create variable foobar; ensures variable created next assignment created @ global scope, not local variable in main.

python scope globals

No comments:

Post a Comment