Default Argument Inconsistency?

Paul Sweeney reverse.ku.oc.issolok at nothypgnal.delrest.co.uk
Tue Apr 27 06:31:12 EDT 2004


That's a great gotcha!

The typo I knew about was that I should have had
    def f(a, L=None):

but as you point out also the 'if' should be more explicitly
    if L is None: L = []

As I said in reply to Diez, I'm new to Python and had switched
in general from my initial style of

  if L is None or L==[]:
to
  if not L:

which was clearly wrong here.  As always, "a little knowledge
is a dangerous thing" :-)


Thanks, (to me ;-) an interesting problem and explanations

Paul


"Peter Otten" <__peter__ at web.de> wrote...

> ... there is one pitfall that will sooner or later bite
> you:
>
> >>> def f(a, L=[]):
> ...     if not L: L = []
> ...     L.append(a)
> ...     return L
> ...
> >>> l1 = ["old"]
> >>> f("new", l1)
> ['old', 'new']
> >>> l1
> ['old', 'new']
> >>> l2 = []
> >>> f("new", l2)
> ['new']
> >>> l2
> []
> >>>
>
> Did you predict the values of l1 and l2 correctly? Congratulations.
> ...





More information about the Python-list mailing list