Having Trouble with Scoping Rules

Michael Spencer mahs at telcopartners.com
Mon Jan 30 22:12:10 EST 2006


Charles Krug wrote:
> List:
> 
...
> # 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?
> 
> Thanx
> 
> 
> Charles
> 
As the traceback says:

 > UnboundLocalError: local variable '_expensiveObject' referenced before
assignment

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
def ExpensiveObject():
     global _expensiveObject # Without this, _expensiveObject is local
                             # because of the assignment below
     if not(_expensiveObject):
         _expensiveObject = "A VERY Expensive object"

     return _expensiveObject


[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.

HTH

Michael





More information about the Python-list mailing list