C-style static variables in Python?

Patrick Maupin pmaupin at gmail.com
Fri Apr 2 20:39:33 CEST 2010


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



More information about the Python-list mailing list