Having Trouble with Scoping Rules

Charles Krug cdkrug at aol.com
Mon Jan 30 21:48:17 EST 2006


I've a module that's not doing what I expect.  My guess is that I don't
quite understand the scoping rules the way I should.

I have an object that's costly to create.  My thought was to create it
at the module level like this:

# expensive Object Module

_expensiveObject = None
def ExpensiveObject():

    if not(_expensiveObject):
        _expensiveObject = "A VERY Expensive object"

    return _expensiveObject

if __name__ == '__main__':
    print _expensiveObject
    print ExpensiveObject()

When I run this module, I get the expected "None" but then I get
UnboundLocalError from the function call when _expensiveObject is

Traceback (most recent call last):
line 310, in RunScript
    exec codeObject in __main__.__dict__
  File "Expensive.py", line 13, in ?
    print ExpensiveObject()
  File "Expensive.py", line 6, in ExpensiveObject
    if not(_expensiveObject):
UnboundLocalError: local variable '_expensiveObject' referenced before

I obviously missed some part of the scoping rules.

What's the correct way to do this?



More information about the Python-list mailing list