3 \documentclass{article
}
6 \section*
{Design rules about global variable dependencies
}
8 I've just noticed a problem in evaluating default arguments of
9 functions in combination with global variables. Consider the following
25 The question arises, what the output of this program will be. I
26 expected the output to be
\verb|
2|, but I observed
\verb|
1|. This
27 behaviour is documented in the ``Python Reference Manual'':
30 Default parameter values are evaluated when the function definition is
31 executed. This means that the expression is evaluated once, when the
32 function is defined, and that that same ``pre-computed'' value is used
33 for each call. This is especially important to understand when a
34 default parameter is a mutable object, such as a list or a dictionary:
35 if the function modifies the object (e.g. by appending an item to a
36 list), the default value is in effect modified. This is generally not
37 what was intended. A way around this is to use None as the default,
38 and explicitly test for it in the body of the function, e.g.:
40 def whats_on_the_telly(penguin=None):
43 penguin.append("property of the zoo")
48 It means that the modification of the scale doesn't effect the default
49 argument evaluation. This effect could easily confuse users of
\PyX.
50 We should therefore avoid constructions where those early evaluations
51 of default arguments are influenced by global variables. Typical
52 candidates are constructors which will convert
\PyX-length using the
53 global scaling settings in
\verb|pyx.unit|. When those classes are
54 used as default arguments of other functions the effect shown above
55 will occure. We should resolve this untimely evaluation by moving
56 \PyX-length interpretations out of the constructors. An alternative
57 solution shown in the quotation of the ``Python Reference Manual'' is
58 considered to be less elegant for the case of interpreting