static keyword

Peter Hansen peter at engcorp.com
Thu Apr 29 10:37:36 EDT 2004


Nick Jacobson wrote:

> I believe the following "static" command would be useful in Python.
[snip]
> Just like in C, the variables i and firstcall are only assigned the
> first time foo() is called.  To get this effect currently, one could
> use default arguments or wrapping the whole thing in a class.  Both of
> these solutions seem like hacks, the above method IMO is more
> Pythonic. :)

I'm not sure how to interpret the smiley, but I'll take it
you weren't actually joking...

Why do you call using OO ("wrapping it in a class", as you say)
a "hack"?  Generally speaking, using objects to contain state
information such as this is exactly what most people would call
the cleanest, best approach.

class HasState:
     def __init__(self):
         self.firstCall = True
         self.i = [10, 11]

     def foo(self):
         if self.firstCall:
             print "First pass"
             self.firstCall = False
         self.i[0] += 1
         print self.i[0]

obj = HasState()
obj.foo()
obj.foo()

Now, without arguing that it has 11 lines instead of 8 to do the
same thing (because then I'd just point out that this was a contrived
example anyway, and that it is more easily extended, and more obvious
what was going on, etc. :-) ), can you describe why you call this is
a "hack"?

-Peter



More information about the Python-list mailing list