A logical consequence of def being an executable statement

December 31, 2005

I've mentioned before that in Python, def is actually an executable statement (in FunctionDefinitionOrder). A logical consequences of this is that default values for function arguments are evaluated only once, when the def runs.

I say this because expressions generally get evaluated when any Python statement runs, so the expressions in things like 'def foobar(a, b=greeble(c), d=None):' are not being an exception. The exception would be if they were not evaluated then and were instead preserved as little lambda expressions to be evaluated later.

On an interesting side note, setting default values for arguments is one of the two places in Python where the same variable name can be in two different scopes simultaneously; the other is invoking a function with keyword arguments. Everywhere else you write 'a=a' the two a's are the same, but in these two cases the a being assigned to is in the new function's scope and the expression's a is in your current scope.

The result can be a little bit confusing, as you can see in StructsWithDefaults. (Which is one reason I like to avoid it.)

Sidebar: mutable default arguments

This means that mutable default arguments are usually not what you want, because if you change them they will stay mutated in subsequent invocations of the function. The usual pattern around this is something like:

def foobar(a, deflst=None):
  if deflst is None:
    deflst = []
  ....
Written on 31 December 2005.
« On Lisp's fundamental data structure
Notes on getting a Solaris hardware inventory »

Page tools: View Source, Add Comment.
Search:
Login: Password:
Atom Syndication: Recent Comments.

Last modified: Sat Dec 31 02:45:49 2005
This dinky wiki is brought to you by the Insane Hackers Guild, Python sub-branch.