What is a function parameter =[] for?

Ian Kelly ian.g.kelly at gmail.com
Thu Nov 19 10:42:00 EST 2015


On Thu, Nov 19, 2015 at 5:45 AM, Steven D'Aprano <steve at pearwood.info> wrote:
> But if you want the default value to be evaluated exactly once, and once
> only, there is no real alternative to early binding. You could use a global
> variable, of course, but that is no solution -- that's a problem waiting to
> happen.

It doesn't have to be a global. In a Python with late binding
defaults, this would work to get early binding:

def f(x=f.default_x):
    ...

f.default_x = something()

Of course, assignment to function attributes is a relatively modern
thing that is only permitted since Python 2.1, whereas function
defaults have been around since at least 1.4, so this wouldn't have
been an option when the semantics were being determined.



More information about the Python-list mailing list