On 2 January 2013 08:12, Chris Angelico <rosuav@gmail.com> wrote:
On Wed, Jan 2, 2013 at 6:29 PM, Antoine Pitrou <solipsis@pitrou.net> wrote:
> Let's call them a compromise then, but calling them a language feature
> sounds delusional. I can't remember ever taking advantage of the fact
> that mutable default arguments are shared accross function invocations.

One common use is caching, as I mentioned earlier (with a contrived
example). Another huge benefit is efficiency - construct a heavy
object once and keep using it. There are others.

It's a feature that can bite people, but no less a feature for that.


A further (and important) use case is introspection. If default values were only added at call time (rather than definition time) then you couldn't introspect the default value - so documentation tools (and other tools) couldn't have access to them.

Added to which, "evaluation at call time" has its own unexpected and weird behaviour. Consider:

x = 3
def fun(a=x):
  pass
del x

With evaluation at call time this code fails - and indeed any *re-binding* of x in the definition scope (at any subsequent time - possibly far removed from the function definition) affects the function.

So default values being bound at definition times have advantages for efficiency and introspection, they have use cases for caching, and it removes some unexpected behaviour. It's definitely a language feature.

All the best,

Michael

 

ChrisA
_______________________________________________
Python-ideas mailing list
Python-ideas@python.org
http://mail.python.org/mailman/listinfo/python-ideas



--
http://www.voidspace.org.uk/

May you do good and not evil
May you find forgiveness for yourself and forgive others
May you share freely, never taking more than you give.
-- the sqlite blessing http://www.sqlite.org/different.html