Having Trouble with Scoping Rules

Charles Krug cdkrug at aol.com
Tue Jan 31 06:12:03 CET 2006


On 2006-01-31, Farshid Lashkari <flashkNO at SPAMgmail.com> wrote:
> You need to declare _expensiveObject as global inside your function. 
> Whenever you assign something to a variable that resides in the global 
> scope inside a function, you need to declare it as global at the 
> beginning of the function. So your function should look like this
>
> def ExpensiveObject():
>      global _expensiveObject
>      if not(_expensiveObject):
>          _expensiveObject = "A VERY Expensive object"
>
>      return _expensiveObject
>
> The documentation will no doubtedly explain it better than I have
>

Not really.  If I'd understood the docs, I wouldn't need to ask here.

Okay, that works in the module where I define the function.  But if I
import the module:

# expensive Object User
import Expensive

print Expensive.ExpensiveObject()

I get the same exception.  That approach most likely isn't going to work
for me, as I need to be able to reuse the costly (to create) object.


Okay THIS seems to be working for me:

# expensive Object Module

_expensiveObject = None
def ExpensiveObject():
    try:
        retval = _expensiveObject
    except UnboundLocalError:
        _expensiveObject = "A VERY Expensive object"
        retval = _expensiveObject

    return retval

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


Which gives me:

>>> import Expensive
>>> a = Expensive.ExpensiveObject()
>>> b = Expensive.ExpensiveObject()
>>> a == b
True
>>> a is b
True
>>> 

I'll try it with my actual class instance to verify.  Anyone see
anything I'm missing?


Thanx






More information about the Python-list mailing list