Having Trouble with Scoping Rules
mahs at telcopartners.com
Mon Jan 30 22:12:10 EST 2006
Charles Krug wrote:
> # expensive Object Module
> _expensiveObject = None
> def ExpensiveObject():
> if not(_expensiveObject):
> _expensiveObject = "A VERY Expensive object"
> return _expensiveObject
> I obviously missed some part of the scoping rules.
> What's the correct way to do this?
As the traceback says:
> UnboundLocalError: local variable '_expensiveObject' referenced before
By assigning to _expensiveObject in the function you make _expensiveObject a
local identifier (no matter which code path is followed). The easiest 'fix' for
your code is to insert a global statement:
_expensiveObject = None
global _expensiveObject # Without this, _expensiveObject is local
# because of the assignment below
_expensiveObject = "A VERY Expensive object"
[See: http://docs.python.org/ref/naming.html for more details]
But there is likely to be a more elegant solution, depending on what your real
code looks like.
More information about the Python-list