C-style static variables in Python?

Ethan Furman ethan at stoneleaf.us
Fri Apr 2 14:21:10 EDT 2010


kj wrote:
> <OO>
> class _Spam(object):
>     @classmethod
>     def _(cls, x, y, z):
>         try:
>             mongo = cls.mongo
>         except AttributeError:
>             mongo = cls.mongo = heavy_lifting_at_runtime()
>         return frobnicate(x, y, z, mongo)
> 
> ham = _Spam._(1, 2, 3)
> </OO>
> 
> 
> Is this really more natural or more readable?  Hmmm.

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~



More information about the Python-list mailing list