[docs] [issue12374] Execution model should explain compile vs definition vs execution time

Nick Coghlan report at bugs.python.org
Sat Jun 25 02:32:09 CEST 2011


Nick Coghlan <ncoghlan at gmail.com> added the comment:

The other directly relevant part is in section 5:

5.1.3 Evaluating Default Arguments
In static languages such as C, function definitions are instructions to the compiler rather than executable statements. This leads to such languages making distinctions between events that occur at run-time and at compile time. In Python, function definitions are statements in their own right, so run-time events related to functions are further divided into events that occur at definition time and at execution time. Definition time refers to the point where the function is defined by the def statement. Execution time refers to the point where the function is called and the body of the function is executed.
Where these distinctions matter the most is in the evaluation of default arguments, as this occurs only once at the time the function is defined. For immutable default values like numbers or the constant value None, this doesn't have any perceptible effect. For mutable defaults like lists and dictionaries, however, it makes a significant difference, as it means a single instance of the object is created at definition time, and is then shared across all invocations of the function that use the default argument value. This can result in unintended side effects. The typical approach to handling this situation is to use None as the default argument, and include code in the body of the function to create the appropriate default value when the parameter is set to None. The following listing shows the difference between the two mechanisms.
[Grab the ODF file if you want to see the code listing]

----------

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


More information about the docs mailing list