Default Parameters to function!

Yuriy Gorvitovskiy yuriy at centricsoftware.com
Wed Mar 15 15:13:44 EST 2000


This is the example:

def Test(Value,iter=5,Map={}):
    if iter>0:
        Map[len(Map)]=Value
        Test(Value,iter-1,Map)
    return Map

def TestCall():
    Map=Test(5)
    print Map
    Map=Test(6)
    print Map


TestCall()

This is the result:

{4: 5, 3: 5, 2: 5, 1: 5, 0: 5}
{9: 6, 8: 6, 7: 6, 6: 6, 5: 6, 4: 5, 3: 5, 2: 5, 1: 5, 0: 5}

This is problem description in Python Manual:

Default parameter values are evaluated when the function definition is
executed. This means that the expression is evaluated once, when the
function is defined, and that same ``pre-computed'' value is used for each
call. This is especially important to understand when a default parameter is
a mutable object, such as a list or a dictionary: if the function modifies
the object (e.g. by appending an item to a list), the default value is in
effect modified. This is generally not what was intended. A way around this
is to use None as the default, and explicitly test for it in the body of the
function, e.g.:


def whats_on_the_telly(penguin=None):
    if penguin is None:
        penguin = []
    penguin.append("property of the zoo")
    return penguin

I want to make a request to the Python developers to change the way of
default parameters initialization from "when function definition is
executed" to "when function executed". I spend half of the days to figure
out this problem. This definition not intuitive. If somebody can give me One
GOOD reason why it this way, I will be appreciate!

[YG]






More information about the Python-list mailing list