Optional parameter object re-used when instantiating multiple objects

Aaron Brady castironpi at gmail.com
Mon Nov 17 07:52:54 CET 2008


On Nov 16, 8:16 pm, Aaron Brady <castiro... at gmail.com> wrote:
> On Nov 16, 12:52 am, Steven D'Aprano <st... at REMOVE-THIS-
> > I've given practical reasons why the
> > Python choice is better. If you want default argument to be created from
> > scratch when the function is called, you can get it with little
> > inconvenience, but the opposite isn't true. It is very difficult to get
> > static default arguments given a hypothetical Python where default
> > arguments are created from scratch. There's no simple, easy idiom that
> > will work. The best I can come up with is a convention:
>
> I'm not so sure.
>
> ## Default evaluated at definition time.  (Current.)
>
> # Static arg.
> def f( a= [] ):
>   ...
>
> # Non-static arg.
> def f( a= None ):
>   if a is None: a= []

Oops.  Forgot one, after the subsequent posts.

# Non-static arg.
@nonstatic( a= list )
def f( a ):
  ...

This can achieve the 'if a is None' effect.  'nonstatic' takes a
callable or a string, '@nonstatic( a= "[]" )'.

I don't see a way to achieve George Sakkis's example:

    if y is None: y = x*x
    if z is None: z = x+y

Without a change to the language (the other options don't need one).

#emulates 'def foo(x, y=`x*x`, z=`x+y`):'
@nonstatic( y= 'x*x' ) #illegal
@nonstatic( z= 'x+y' ) #illegal
def foo(x, y, z):
    return x+y+z



More information about the Python-list mailing list