mutable default parameter problem [Prothon]
Andrea Griffini
agriff at tin.it
Wed Jun 16 02:53:15 EDT 2004
On Tue, 15 Jun 2004 22:01:19 -0800, Troy Melhase <troy at gci.net> wrote:
>Seriously, you see a "wart" and a "problem". I see a pleasant side-effect of
>the documented semantics. True, new folks are surprised by the behavior, but
>once it's understood, it becomes more powerful.
>
>How do you intend to account for code like this:
>
>def F(a, b, cache={}):
> try:
> return cache[(a,b)]
> except (IndexError, ):
> value = cache[(a,b)] = do_some_long_calc(a,b)
> return value
I'm new to python. To my eyes this is a pretty poor attempt to
have static variables. I've implemented in the past a few
scripting languages, and it's not really difficult to
implement static variables... it's quite surprising for me
there's no such a concept in python and just that wart...
hmmm... excuse me... that bad smelling wart has to be used instead.
>Or even this:
>
>shared_cache = {}
>
>def F(a, b, cache=shared_cache):
> ...
A global you mean ? Why not just saying "global shared_cache"
at the start of the function ?
If you need more power than a global then you probably a
(callable) class is going to serve you better than a function.
Is really a feature that if someone passes (by mistake) an extra
parameter to the function the script silently swallows it and
behaves strangely ? Or you also double-wrap the function, so
that a(x,y) calls real_a(x,y,cache=[]) ?
>Of course you can argue that this is bad style, but the counter argument is
>just as strong: this is quite pythonic and quite readable.
Pythonic ? In the sense that this is for example more explicit ?
Are you kidding ?
>Python is a tool, and you decrease the utility of that tool when you limit
>it's idioms.
>
>> How much Python code would these different proposals break?
>
>A lot. I ran this:
This doesn't surprise me. Static variables are useful when you
don't really need the power of a class instance. Too bad that
them are missing in python, and for unknown (to me) reasons
they haven't been added in the evolution of the language.
>$ find /usr/lib/python2.3/ -name "*.py" -exec grep "def.*=\[\]" {} \; | wc
>
>And see 67 instances just in the standard library. Multiply that by a factor
>of 1000, 10000 or more to reflect code in the field, and you might start to
>understand the significance of changing the language definition.
That something is used is one thing. That something is elegant
is another.
Andrea
More information about the Python-list
mailing list