Having Trouble with Scoping Rules

Charles Krug cdkrug at aol.com
Tue Jan 31 07:39:59 EST 2006


On 2006-01-31, Fredrik Lundh <fredrik at pythonware.com> wrote:
>
>     def ExpensiveObject():
>         global _expensiveObject
>         if _expensiveObject is None:
>             _expensiveObject = "A VERY Expensive object"
>             print "CREATED VERY EXPENSIVE OBJECT"
>         return _expensiveObject
>
>     if __name__ == "__main__":
>         print _expensiveObject
>         print ExpensiveObject()
>         print ExpensiveObject()
>         print ExpensiveObject()
>
> which prints
>
>     None
>     CREATED VERY EXPENSIVE OBJECT
>     A VERY Expensive object
>     A VERY Expensive object
>     A VERY Expensive object
>
> and works perfectly fine if you import it from another module:
>

Ah, I had another error that broke it on import.  Testing with a
dictionary showed me the "creates another object" error.  Using a string
constant for that was just a "between the ears" problem that would have
shown me the error much quicker.

Thanks.




More information about the Python-list mailing list