Newbie asks about static variables...

Evan Simpson evan at tokenexchange.com
Tue May 4 15:00:26 EDT 1999


If you *really*, *really* want a function-private static, you could write
this:

def killParrot(no_of_calls=[0]):
    # do stuff
    print "Number of calls is %d" % no_of_calls[0]
    no_of_calls[0] = no_of_calls[0] + 1

>>> killParrot()
Number of calls is 0
>>> killParrot()
Number of calls is 1
>>>

This is also a case study in the dangers of mutable default parameters.

I wouldn't normally mention a wierd idiom like this in the presence of a
newbie, but I'm feeling evil.

with-a-stomach-flu-and-in-the-mood-to-spread-the-suffering-ly y'rs
Evan Simpson




Martijn Faassen wrote in message <372F3FFF.E247C288 at pop.vet.uu.nl>...
stephen.allison at cenes.co.uk wrote:
[snip static variable example in C]
> If i try to do copy the above 'directly' into python no_of_calls is reset
each
> time the function is called (which is fair enough), and I can only acjieve
the
> required behaviour by having decaling number_of_calls as 'global', which
> doesn't seem very elegant.  It seems a funny thing not to be in a language
> which is other wise very nice.  Perhaps I'm not 'thinking in python' yet,
can
> anyone shed some light?

Well, using a global variable would indeed be one way. One need not be
as worried with global variables in Python, as there's a nice module
system that puts them in their own namespaces. If you prepend your
global variable with a _ then it doesn't get imported, even if you use
'from <module> import *'.

Another option is to use a class for this kind of behavior.

class Foo:
    amount = 0 # class variable, could use instance variable too
    def __call__(self):
        """Objects of this class can be called like functions.
        """
        self.amount = self.amount + 1
        print "You called me %s times." % self.amount
foo = Foo() # instantiate a single instance as a function

# call the 'function'
foo()
foo()
foo()

Regards, and good luck,

Martijn






More information about the Python-list mailing list