Default arguments, object sharing, name lookup and others

Maciej Sobczak no.spam at no.smap.com
Tue Dec 23 04:33:47 EST 2003


Hi,

Maciej Sobczak wrote:

> Playing around with the Python Tutorial I found the following definition:
> 
> def f(a,L=[]):
>     L.append(a)
>     return L
[...]

Thank you very much for your replies.
The most enlightening was the one mentioning func_defaults.


For your *amusement only*, here is the C++ analogy I devised for myself 
to better understand what is going on:

The Python function definition is like definition *and* creation of C++ 
function object, initialized with what should be the default value for 
further function calls:

class Fun
{
public:
     Fun(shared_ptr<Any> default_value)
         : def_val_(default_value) {}
     Any operator()(shared_ptr<Any> arg)
     {
	// here goes the body of the function
         // ...
     }
     Any operator()()
     {
         return operator()(def_val_);
     }
private:
     shared_ptr<Any> def_val_;
};

(of course, this applies to *one-argument* function with default 
argument value)

Once the function object is created, it stores the default value for 
future. When it is called without arguments, it retrieves the default 
value from where it is stored.
Now, the hard core:
- If I do some mutating operation on the default value (like list append 
or insert operation), I can see it the next time I call the function.
- If I reassign the arg shared pointer to something else (for example, 
to the new value like in "L = L + a" Python expression), it does not 
influence the object pointed by def_val_ pointer and is visible only to 
the end of the current flow in operator(), when the local arg variable 
goes out of scope.

Regards to all,

-- 
Maciej Sobczak : http://www.msobczak.com/
Programming    : http://www.msobczak.com/prog/





More information about the Python-list mailing list