graph.dat added
[PyX/mjg.git] / design / global.tex
blob80a40c15e40ed98564c03cafb234b79e481fcbd0
1 % $Header$
3 \documentclass{article}
4 \usepackage{pyx}
5 \begin{document}
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
10 example:
12 \begin{verbatim}
13 scale = 1
15 def a():
16 print scale
18 def b(x = a()):
19 pass
21 scale = 2
22 b()
23 \end{verbatim}
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'':
29 \begin{quote}
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.:
39 \begin{verbatim}
40 def whats_on_the_telly(penguin=None):
41 if penguin is None:
42 penguin = []
43 penguin.append("property of the zoo")
44 return penguin
45 \end{verbatim}
46 \end{quote}
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
59 \PyX-length.
60 \end{document}