Re: Having Trouble with Scoping Rules
Available news archives: comp.lang.tcl - comp.lang.python - comp.security.firewalls - sci.crypt - comp.lang.php - comp.lang.javascript
Google
 
Web news.hping.org


comp.lang.python archive

Re: Having Trouble with Scoping Rules

From: Charles Krug <cdkrug@aol.com>
Date: Tue Jan 31 2006 - 06:12:03 CET

On 2006-01-31, Farshid Lashkari <flashkNO@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
Received on Tue Feb 7 20:19:03 2006