Optional parameter object re-used when instantiating multiple objects

George Sakkis george.sakkis at gmail.com
Wed Nov 19 14:26:54 EST 2008


On Nov 19, 1:05 pm, Dennis Lee Bieber <wlfr... at ix.netcom.com> wrote:

> On Wed, 19 Nov 2008 05:41:57 -0800 (PST), Rick Giuly
> <rgiuly.gr... at yahoo.com> declaimed the following in comp.lang.python:
>
>
>
> > (By "better" I mean that over many years of time programmers will be
> > more productive because the language will be learned a bit faster with
> > a fewer surprises - and still retain its power.)
>
>         Your opinion... I'm sure there are some libraries out there that
> rely upon the current behavior

That's a straw man; of course they rely on it since they can. The same
would be even more true if the opposite behavior was selected from the
beginning, many more libraries would rely on it instead of (ab)using
None as default.

>  -- not to mention the hit on processing
> speed.

That's the only argument that may worth some merit. It's interesting
though that C++, a language much more obsessed with performance, picks
the runtime semantics:

#include <iostream>
using namespace std;

int a = 1;

int f(int a) {
  cout << "f(" << a << ") called\n";
  return a;
}

int g(int x = f(a)) { return x; }

int main() {
  cout << g() << endl;
  a = 2;
  cout << g() << endl;
}

#===== output ==============
f(1) called
1
f(2) called
2

>         I wouldn't expect a language like Ada to somehow re-evaluate a
> default argument on each call; why would I expect Python to do such?

Again, non sequitur. Python is not Ada (neither is C++, which does the
expected thing in this case).

>         Besides, learning is good for one -- and having something like this
> in Python gives one an excuse to learn something about language
> implementation choices <G>
>
>         And what behavior do you expect from:
>
>
>
> >>> d1 = [ 1, 2 ]
> >>> def what(arg = d1):
> ...     print arg
>
> ...    
> >>> what()
> [1, 2]
> >>> d1 = ( 3.14159, 2.78)
> >>> what()
> [1, 2]
>
>         If one does reevaluation of the default on each call, the second
> call should be printing
>
> (3.14159, 2.78)
>
>
>
> >>> del d1
> >>> what()
> [1, 2]
>
>         And that sequence would result in an exception
>
> Traceback (most recent call last):
>   File "<interactive input>", line 1, in <module>
> NameError: name 'd1' is not defined
>
>         Do you really want a "default" argument that changes value depending
> upon actions performed in the /surrounding/ scope?

Yes, the surrounding scope in this case is the global scope; changing
or deleting globals has by definition global reach. Regardless, how
common is this usage in real code ? I believe an order of magnitude
less than the need for fresh mutable objects.

George



More information about the Python-list mailing list