C-style static variables in Python?

Patrick Maupin pmaupin at gmail.com
Fri Apr 2 15:39:16 EDT 2010


On Apr 2, 2:38 pm, Ethan Furman <et... at stoneleaf.us> wrote:
> 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~

Well, I think the whole discussion has basically been about personal
preference.  OTOH, but if you call the function a few million times,
you might find the cost of try/except to be something that you would
rather not incur -- it might become a performance issue rather than a
personal choice issue.  On the other OTHER hand, if you call the
function a few billion times, performance weighs more heavily in favor
of the closure approach rather than the object approach, since local
variable lookup is so much cheaper.

Regards,
Pat



More information about the Python-list mailing list