C-style static variables in Python?
Ethan Furman
ethan at stoneleaf.us
Fri Apr 2 15:38:56 EDT 2010
Patrick Maupin wrote:
> On Apr 2, 1:21 pm, Ethan Furman <et... at stoneleaf.us> wrote:
>> For this type of situation, my preference would be:
>>
>> class spam(object):
>> def __call__(self, x, y, z):
>> try:
>> mongo = self.mongo
>> except AttributeError:
>> mongo = self.mongo = heavy_lifting_at_runtime()
>> return frobnicate(x, y, z, mongo)
>> spam = spam()
>>
>> No extra objects, out-of-place underscores, etc.
>>
>> ~Ethan~
>
> Well, I'm not a big fan of unnecessary try/except, so I would at least
> change it to:
>
> class spam(object):
> def __getattr__(self, name):
> if name != 'mongo':
> raise AttributeError
> self.mongo = heavy_lifting_at_runtime()
> return self.mongo
> def __call__(self, x, y, z):
> return frobnicate(x, y, z, self.mongo)
> spam = spam()
>
> Regards,
> Pat
Sounds like a personal preference issue, rather than a necessary /
unnecessary issue -- after all, if you call that function a thousand
times, only once is mongo not defined... clearly the exception. ;)
~Ethan~
More information about the Python-list
mailing list