Re: Having Trouble with Scoping Rules
- From: Charles Krug <cdkrug@xxxxxxx>
- Date: Mon, 30 Jan 2006 23:12:03 -0600
On 2006-01-31, Farshid Lashkari <flashkNO@xxxxxxxxxxxxx> 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
.
- Follow-Ups:
- Re: Having Trouble with Scoping Rules
- From: Fredrik Lundh
- Re: Having Trouble with Scoping Rules
- References:
- Having Trouble with Scoping Rules
- From: Charles Krug
- Re: Having Trouble with Scoping Rules
- From: Farshid Lashkari
- Having Trouble with Scoping Rules
- Prev by Date: Re: A simple question string.replace
- Next by Date: wxPython Conventions
- Previous by thread: Re: Having Trouble with Scoping Rules
- Next by thread: Re: Having Trouble with Scoping Rules
- Index(es):