[Tutor] default argument frustration

Alan Gauld alan.gauld at freenet.co.uk
Sun Feb 13 09:58:51 CET 2005


> Alan was saying that there is no other obvious way for Python to do
it.
>
> What I am still not clear on it is why Alan's claim is true. (Not
> doubting it is, but would like to get why it is.)

Doubt away, my knowledge of Python internals is largely intuitive,
I've never got round to reading the C code!

But as I understand it when Python defs a function it creates
a dictionary object at the module level that handles the naming.
When the function executes, the local names have their own namespace.
In Lisp, again as I understand it, the namespace is effectively
passed around with the function (rather than being fixed at module
level) so it is easier for the function to modify its own context.
Dynamically rebinding the default value in Python would require
an external lookup at the module level which would be more complex
and expensive.

> Is this the rough idea this?:
>
> The def statement is executed only once, and thus the default
argument
> is calculated just the once, too (on building of the function
object).
> So, any way around this feature of Python would either require that
> defs be executed each time a function is called (giant performance
hit
> across the board even if doable) or require the addition of a new
> reserved word, say redef,

I don't know if the whole def would need to be redone but the binding
of function and parameter values would, I think. But as I say most of
this is intuitive knowledge - i.e. based on how I think *I* would have
built the behaviour I observe!

> good thing, and enough to kill such a redef idea, if the performance
> issue wasn't.

I think its probably possible to change the mechanism but I suspect
it would add significantly to the function overgead - which is already
quite high in Python.

But I'm happy to be enlightened by anyone who *really* knows how and
why this stuff works.

And in thinking about this I'm stimulated to ask, does anyone know
how default arguments work in a threaded context? What happens if
two threads try to modify the content of a mutable default argument
at the same time?

Alan G.



More information about the Tutor mailing list