[issue8762] default value in constructor not unique across objects

Ray.Allen report at bugs.python.org
Wed May 19 04:08:06 CEST 2010


Ray.Allen <ysj.ray at gmail.com> added the comment:

Here is the explanation from Python Language Reference 7.6: Function Definitions
"""
When one or more top-level parameters have the form parameter = expression, the function is said to have ``default parameter values.'' For a parameter with a default value, the corresponding argument may be omitted from a call, in which case the parameter's default value is substituted. If a parameter has a default value, all following parameters must also have a default value -- this is a syntactic restriction that is not expressed by the grammar. 
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 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
"""

----------
nosy: +ysj.ray

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue8762>
_______________________________________


More information about the Python-bugs-list mailing list