Python mutable default arguments

A concept I found interesting coming from the C++ world in Python is the parameter passing convention and the particular behavior with a mutable default argument such as a list.

In C++ the arguments can be passed by value or reference. This is clear and such arguments are pushed into the stack. In the other side, in Python, parameters are passed by object or call-by-object. A parameter is passed by reference, except when such parameter is updated then the parameter is passed b y value. Kind of weird, isn’t?

For mutable objects, such as a list, individual elements can be changed at the caller’s level.

Careful about having a default list argument as this list object will be created once in function definition then reused in every call!

In C++ there is something weird when having default arguments with virtual functions. These are not part of signature. Default values are evaluated at compile time.

If base class calls virtual function, in compile time the default value will be substituted accordingly to the defaut value of the object that points.

Leave a Reply

Your email address will not be published. Required fields are marked *