C
Charles Krug
List:
I've a module that's not doing what I expect. My guess is that I don't
quite understand the scoping rules the way I should.
I have an object that's costly to create. My thought was to create it
at the module level like this:
# expensive Object Module
_expensiveObject = None
def ExpensiveObject():
if not(_expensiveObject):
_expensiveObject = "A VERY Expensive object"
return _expensiveObject
if __name__ == '__main__':
print _expensiveObject
print ExpensiveObject()
When I run this module, I get the expected "None" but then I get
UnboundLocalError from the function call when _expensiveObject is
accessed:
Traceback (most recent call last):
File
"C:\Python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py",
line 310, in RunScript
exec codeObject in __main__.__dict__
File "Expensive.py", line 13, in ?
print ExpensiveObject()
File "Expensive.py", line 6, in ExpensiveObject
if not(_expensiveObject):
UnboundLocalError: local variable '_expensiveObject' referenced before
assignment
I obviously missed some part of the scoping rules.
What's the correct way to do this?
Thanx
Charles
I've a module that's not doing what I expect. My guess is that I don't
quite understand the scoping rules the way I should.
I have an object that's costly to create. My thought was to create it
at the module level like this:
# expensive Object Module
_expensiveObject = None
def ExpensiveObject():
if not(_expensiveObject):
_expensiveObject = "A VERY Expensive object"
return _expensiveObject
if __name__ == '__main__':
print _expensiveObject
print ExpensiveObject()
When I run this module, I get the expected "None" but then I get
UnboundLocalError from the function call when _expensiveObject is
accessed:
Traceback (most recent call last):
File
"C:\Python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py",
line 310, in RunScript
exec codeObject in __main__.__dict__
File "Expensive.py", line 13, in ?
print ExpensiveObject()
File "Expensive.py", line 6, in ExpensiveObject
if not(_expensiveObject):
UnboundLocalError: local variable '_expensiveObject' referenced before
assignment
I obviously missed some part of the scoping rules.
What's the correct way to do this?
Thanx
Charles