From: emile at fenx.com (Emile van Sebille)
Date: Tue, 4 May 1999 18:17:41 -0700
Subject: Newbie asks about static variables...
References: <7gn9a7$hg9$1@nnrp1.dejanews.com> <372F3FFF.E247C288@pop.vet.uu.nl> <8sHX2.66$eD1.21692@news.corridex.com>
Message-ID: <01NX2.25$VL2.3392@news.direcpc.com>
Content-Length: 1712
X-UID: 1914                                                 

Being also new at Python, doesn't your example follow the example from
section 4.7 of the tutorial?

Why is this *evil*?  It's right there in the tutorial.  </aside - I really
do believe everything I read> What is Guido not saying? What are the
dangers?  Where is the case study?

</start paste from section 4.7>
Important warning: The default value is evaluated only once. This makes a
difference when the default is a mutable object such as a list or
dictionary. For example, the following function accumulates the arguments
passed to it on subsequent calls:


def f(a, l = []):
    l.append(a)
    return l
print f(1)
print f(2)
print f(3)

This will print


[1]
[1, 2]
[1, 2, 3]

If you don't want the default to be shared between subsequent calls, you can
write the function like this instead:


def f(a, l = None):
    if l is None:
        l = []
    l.append(a)

</end paste>

trying-my-best-to-keep-up-and-make-sense-of-it-all-ly y'rs

Emile van Sebille
emile at fenx.com
-------------------


Evan Simpson <evan at tokenexchange.com> wrote in message
news:8sHX2.66$eD1.21692 at news.corridex.com...
> 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
>






