blob: 0bc94118951c3fd4b64d65e9398fcc31d5614ada [file] [log] [blame]
Georg Brandld7413152009-10-11 21:25:26 +00001:tocdepth: 2
2
3===============
4Programming FAQ
5===============
6
7.. contents::
8
9General Questions
10=================
11
12Is there a source code level debugger with breakpoints, single-stepping, etc.?
13------------------------------------------------------------------------------
14
15Yes.
16
17The pdb module is a simple but adequate console-mode debugger for Python. It is
18part of the standard Python library, and is :mod:`documented in the Library
19Reference Manual <pdb>`. You can also write your own debugger by using the code
20for pdb as an example.
21
22The IDLE interactive development environment, which is part of the standard
23Python distribution (normally available as Tools/scripts/idle), includes a
24graphical debugger. There is documentation for the IDLE debugger at
25http://www.python.org/idle/doc/idle2.html#Debugger.
26
27PythonWin is a Python IDE that includes a GUI debugger based on pdb. The
28Pythonwin debugger colors breakpoints and has quite a few cool features such as
29debugging non-Pythonwin programs. Pythonwin is available as part of the `Python
30for Windows Extensions <http://sourceforge.net/projects/pywin32/>`__ project and
31as a part of the ActivePython distribution (see
32http://www.activestate.com/Products/ActivePython/index.html).
33
34`Boa Constructor <http://boa-constructor.sourceforge.net/>`_ is an IDE and GUI
35builder that uses wxWidgets. It offers visual frame creation and manipulation,
36an object inspector, many views on the source like object browsers, inheritance
37hierarchies, doc string generated html documentation, an advanced debugger,
38integrated help, and Zope support.
39
40`Eric <http://www.die-offenbachs.de/eric/index.html>`_ is an IDE built on PyQt
41and the Scintilla editing component.
42
43Pydb is a version of the standard Python debugger pdb, modified for use with DDD
44(Data Display Debugger), a popular graphical debugger front end. Pydb can be
45found at http://bashdb.sourceforge.net/pydb/ and DDD can be found at
46http://www.gnu.org/software/ddd.
47
48There are a number of commercial Python IDEs that include graphical debuggers.
49They include:
50
51* Wing IDE (http://wingware.com/)
52* Komodo IDE (http://www.activestate.com/Products/Komodo)
53
54
55Is there a tool to help find bugs or perform static analysis?
56-------------------------------------------------------------
57
58Yes.
59
60PyChecker is a static analysis tool that finds bugs in Python source code and
61warns about code complexity and style. You can get PyChecker from
62http://pychecker.sf.net.
63
64`Pylint <http://www.logilab.org/projects/pylint>`_ is another tool that checks
65if a module satisfies a coding standard, and also makes it possible to write
66plug-ins to add a custom feature. In addition to the bug checking that
67PyChecker performs, Pylint offers some additional features such as checking line
68length, whether variable names are well-formed according to your coding
69standard, whether declared interfaces are fully implemented, and more.
Georg Brandl495f7b52009-10-27 15:28:25 +000070http://www.logilab.org/card/pylint_manual provides a full list of Pylint's
71features.
Georg Brandld7413152009-10-11 21:25:26 +000072
73
74How can I create a stand-alone binary from a Python script?
75-----------------------------------------------------------
76
77You don't need the ability to compile Python to C code if all you want is a
78stand-alone program that users can download and run without having to install
79the Python distribution first. There are a number of tools that determine the
80set of modules required by a program and bind these modules together with a
81Python binary to produce a single executable.
82
83One is to use the freeze tool, which is included in the Python source tree as
84``Tools/freeze``. It converts Python byte code to C arrays; a C compiler you can
85embed all your modules into a new program, which is then linked with the
86standard Python modules.
87
88It works by scanning your source recursively for import statements (in both
89forms) and looking for the modules in the standard Python path as well as in the
90source directory (for built-in modules). It then turns the bytecode for modules
91written in Python into C code (array initializers that can be turned into code
92objects using the marshal module) and creates a custom-made config file that
93only contains those built-in modules which are actually used in the program. It
94then compiles the generated C code and links it with the rest of the Python
95interpreter to form a self-contained binary which acts exactly like your script.
96
97Obviously, freeze requires a C compiler. There are several other utilities
98which don't. One is Thomas Heller's py2exe (Windows only) at
99
100 http://www.py2exe.org/
101
102Another is Christian Tismer's `SQFREEZE <http://starship.python.net/crew/pirx>`_
103which appends the byte code to a specially-prepared Python interpreter that can
104find the byte code in the executable.
105
106Other tools include Fredrik Lundh's `Squeeze
107<http://www.pythonware.com/products/python/squeeze>`_ and Anthony Tuininga's
108`cx_Freeze <http://starship.python.net/crew/atuining/cx_Freeze/index.html>`_.
109
110
111Are there coding standards or a style guide for Python programs?
112----------------------------------------------------------------
113
114Yes. The coding style required for standard library modules is documented as
115:pep:`8`.
116
117
118My program is too slow. How do I speed it up?
119---------------------------------------------
120
121That's a tough one, in general. There are many tricks to speed up Python code;
122consider rewriting parts in C as a last resort.
123
124In some cases it's possible to automatically translate Python to C or x86
125assembly language, meaning that you don't have to modify your code to gain
126increased speed.
127
128.. XXX seems to have overlap with other questions!
129
130`Pyrex <http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/>`_ can compile a
131slightly modified version of Python code into a C extension, and can be used on
132many different platforms.
133
134`Psyco <http://psyco.sourceforge.net>`_ is a just-in-time compiler that
135translates Python code into x86 assembly language. If you can use it, Psyco can
136provide dramatic speedups for critical functions.
137
138The rest of this answer will discuss various tricks for squeezing a bit more
139speed out of Python code. *Never* apply any optimization tricks unless you know
140you need them, after profiling has indicated that a particular function is the
141heavily executed hot spot in the code. Optimizations almost always make the
142code less clear, and you shouldn't pay the costs of reduced clarity (increased
143development time, greater likelihood of bugs) unless the resulting performance
144benefit is worth it.
145
146There is a page on the wiki devoted to `performance tips
147<http://wiki.python.org/moin/PythonSpeed/PerformanceTips>`_.
148
149Guido van Rossum has written up an anecdote related to optimization at
150http://www.python.org/doc/essays/list2str.html.
151
152One thing to notice is that function and (especially) method calls are rather
153expensive; if you have designed a purely OO interface with lots of tiny
154functions that don't do much more than get or set an instance variable or call
155another method, you might consider using a more direct way such as directly
156accessing instance variables. Also see the standard module :mod:`profile` which
157makes it possible to find out where your program is spending most of its time
158(if you have some patience -- the profiling itself can slow your program down by
159an order of magnitude).
160
161Remember that many standard optimization heuristics you may know from other
162programming experience may well apply to Python. For example it may be faster
163to send output to output devices using larger writes rather than smaller ones in
164order to reduce the overhead of kernel system calls. Thus CGI scripts that
165write all output in "one shot" may be faster than those that write lots of small
166pieces of output.
167
168Also, be sure to use Python's core features where appropriate. For example,
169slicing allows programs to chop up lists and other sequence objects in a single
170tick of the interpreter's mainloop using highly optimized C implementations.
171Thus to get the same effect as::
172
173 L2 = []
174 for i in range[3]:
175 L2.append(L1[i])
176
177it is much shorter and far faster to use ::
178
179 L2 = list(L1[:3]) # "list" is redundant if L1 is a list.
180
181Note that the functionally-oriented builtins such as :func:`map`, :func:`zip`,
182and friends can be a convenient accelerator for loops that perform a single
183task. For example to pair the elements of two lists together::
184
185 >>> zip([1,2,3], [4,5,6])
186 [(1, 4), (2, 5), (3, 6)]
187
188or to compute a number of sines::
189
190 >>> map( math.sin, (1,2,3,4))
191 [0.841470984808, 0.909297426826, 0.14112000806, -0.756802495308]
192
193The operation completes very quickly in such cases.
194
195Other examples include the ``join()`` and ``split()`` methods of string objects.
196For example if s1..s7 are large (10K+) strings then
197``"".join([s1,s2,s3,s4,s5,s6,s7])`` may be far faster than the more obvious
198``s1+s2+s3+s4+s5+s6+s7``, since the "summation" will compute many
199subexpressions, whereas ``join()`` does all the copying in one pass. For
200manipulating strings, use the ``replace()`` method on string objects. Use
201regular expressions only when you're not dealing with constant string patterns.
202Consider using the string formatting operations ``string % tuple`` and ``string
203% dictionary``.
204
205Be sure to use the :meth:`list.sort` builtin method to do sorting, and see the
206`sorting mini-HOWTO <http://wiki.python.org/moin/HowTo/Sorting>`_ for examples
207of moderately advanced usage. :meth:`list.sort` beats other techniques for
208sorting in all but the most extreme circumstances.
209
210Another common trick is to "push loops into functions or methods." For example
211suppose you have a program that runs slowly and you use the profiler to
212determine that a Python function ``ff()`` is being called lots of times. If you
213notice that ``ff ()``::
214
215 def ff(x):
216 ... # do something with x computing result...
217 return result
218
219tends to be called in loops like::
220
221 list = map(ff, oldlist)
222
223or::
224
225 for x in sequence:
226 value = ff(x)
227 ... # do something with value...
228
229then you can often eliminate function call overhead by rewriting ``ff()`` to::
230
231 def ffseq(seq):
232 resultseq = []
233 for x in seq:
234 ... # do something with x computing result...
235 resultseq.append(result)
236 return resultseq
237
238and rewrite the two examples to ``list = ffseq(oldlist)`` and to::
239
240 for value in ffseq(sequence):
241 ... # do something with value...
242
243Single calls to ``ff(x)`` translate to ``ffseq([x])[0]`` with little penalty.
244Of course this technique is not always appropriate and there are other variants
245which you can figure out.
246
247You can gain some performance by explicitly storing the results of a function or
248method lookup into a local variable. A loop like::
249
250 for key in token:
251 dict[key] = dict.get(key, 0) + 1
252
253resolves ``dict.get`` every iteration. If the method isn't going to change, a
254slightly faster implementation is::
255
256 dict_get = dict.get # look up the method once
257 for key in token:
258 dict[key] = dict_get(key, 0) + 1
259
260Default arguments can be used to determine values once, at compile time instead
261of at run time. This can only be done for functions or objects which will not
262be changed during program execution, such as replacing ::
263
264 def degree_sin(deg):
265 return math.sin(deg * math.pi / 180.0)
266
267with ::
268
269 def degree_sin(deg, factor=math.pi/180.0, sin=math.sin):
270 return sin(deg * factor)
271
272Because this trick uses default arguments for terms which should not be changed,
273it should only be used when you are not concerned with presenting a possibly
274confusing API to your users.
275
276
277Core Language
278=============
279
R. David Murrayc04a6942009-11-14 22:21:32 +0000280Why am I getting an UnboundLocalError when the variable has a value?
281--------------------------------------------------------------------
Georg Brandld7413152009-10-11 21:25:26 +0000282
R. David Murrayc04a6942009-11-14 22:21:32 +0000283It can be a surprise to get the UnboundLocalError in previously working
284code when it is modified by adding an assignment statement somewhere in
285the body of a function.
Georg Brandld7413152009-10-11 21:25:26 +0000286
R. David Murrayc04a6942009-11-14 22:21:32 +0000287This code:
Georg Brandld7413152009-10-11 21:25:26 +0000288
R. David Murrayc04a6942009-11-14 22:21:32 +0000289 >>> x = 10
290 >>> def bar():
291 ... print(x)
292 >>> bar()
293 10
Georg Brandld7413152009-10-11 21:25:26 +0000294
R. David Murrayc04a6942009-11-14 22:21:32 +0000295works, but this code:
Georg Brandld7413152009-10-11 21:25:26 +0000296
R. David Murrayc04a6942009-11-14 22:21:32 +0000297 >>> x = 10
298 >>> def foo():
299 ... print(x)
300 ... x += 1
Georg Brandld7413152009-10-11 21:25:26 +0000301
R. David Murrayc04a6942009-11-14 22:21:32 +0000302results in an UnboundLocalError:
Georg Brandld7413152009-10-11 21:25:26 +0000303
R. David Murrayc04a6942009-11-14 22:21:32 +0000304 >>> foo()
305 Traceback (most recent call last):
306 ...
307 UnboundLocalError: local variable 'x' referenced before assignment
308
309This is because when you make an assignment to a variable in a scope, that
310variable becomes local to that scope and shadows any similarly named variable
311in the outer scope. Since the last statement in foo assigns a new value to
312``x``, the compiler recognizes it as a local variable. Consequently when the
313earlier ``print x`` attempts to print the uninitialized local variable and
314an error results.
315
316In the example above you can access the outer scope variable by declaring it
317global:
318
319 >>> x = 10
320 >>> def foobar():
321 ... global x
322 ... print(x)
323 ... x += 1
324 >>> foobar()
325 10
326
327This explicit declaration is required in order to remind you that (unlike the
328superficially analogous situation with class and instance variables) you are
329actually modifying the value of the variable in the outer scope:
330
331 >>> print(x)
332 11
333
334You can do a similar thing in a nested scope using the :keyword:`nonlocal`
335keyword:
336
337 >>> def foo():
338 ... x = 10
339 ... def bar():
340 ... nonlocal x
341 ... print(x)
342 ... x += 1
343 ... bar()
344 ... print(x)
345 >>> foo()
346 10
347 11
Georg Brandld7413152009-10-11 21:25:26 +0000348
349
350What are the rules for local and global variables in Python?
351------------------------------------------------------------
352
353In Python, variables that are only referenced inside a function are implicitly
354global. If a variable is assigned a new value anywhere within the function's
355body, it's assumed to be a local. If a variable is ever assigned a new value
356inside the function, the variable is implicitly local, and you need to
357explicitly declare it as 'global'.
358
359Though a bit surprising at first, a moment's consideration explains this. On
360one hand, requiring :keyword:`global` for assigned variables provides a bar
361against unintended side-effects. On the other hand, if ``global`` was required
362for all global references, you'd be using ``global`` all the time. You'd have
363to declare as global every reference to a builtin function or to a component of
364an imported module. This clutter would defeat the usefulness of the ``global``
365declaration for identifying side-effects.
366
367
368How do I share global variables across modules?
369------------------------------------------------
370
371The canonical way to share information across modules within a single program is
372to create a special module (often called config or cfg). Just import the config
373module in all modules of your application; the module then becomes available as
374a global name. Because there is only one instance of each module, any changes
375made to the module object get reflected everywhere. For example:
376
377config.py::
378
379 x = 0 # Default value of the 'x' configuration setting
380
381mod.py::
382
383 import config
384 config.x = 1
385
386main.py::
387
388 import config
389 import mod
390 print config.x
391
392Note that using a module is also the basis for implementing the Singleton design
393pattern, for the same reason.
394
395
396What are the "best practices" for using import in a module?
397-----------------------------------------------------------
398
399In general, don't use ``from modulename import *``. Doing so clutters the
400importer's namespace. Some people avoid this idiom even with the few modules
401that were designed to be imported in this manner. Modules designed in this
Georg Brandld404fa62009-10-13 16:55:12 +0000402manner include :mod:`tkinter`, and :mod:`threading`.
Georg Brandld7413152009-10-11 21:25:26 +0000403
404Import modules at the top of a file. Doing so makes it clear what other modules
405your code requires and avoids questions of whether the module name is in scope.
406Using one import per line makes it easy to add and delete module imports, but
407using multiple imports per line uses less screen space.
408
409It's good practice if you import modules in the following order:
410
4111. standard library modules -- e.g. ``sys``, ``os``, ``getopt``, ``re``)
4122. third-party library modules (anything installed in Python's site-packages
413 directory) -- e.g. mx.DateTime, ZODB, PIL.Image, etc.
4143. locally-developed modules
415
416Never use relative package imports. If you're writing code that's in the
417``package.sub.m1`` module and want to import ``package.sub.m2``, do not just
418write ``import m2``, even though it's legal. Write ``from package.sub import
419m2`` instead. Relative imports can lead to a module being initialized twice,
420leading to confusing bugs.
421
422It is sometimes necessary to move imports to a function or class to avoid
423problems with circular imports. Gordon McMillan says:
424
425 Circular imports are fine where both modules use the "import <module>" form
426 of import. They fail when the 2nd module wants to grab a name out of the
427 first ("from module import name") and the import is at the top level. That's
428 because names in the 1st are not yet available, because the first module is
429 busy importing the 2nd.
430
431In this case, if the second module is only used in one function, then the import
432can easily be moved into that function. By the time the import is called, the
433first module will have finished initializing, and the second module can do its
434import.
435
436It may also be necessary to move imports out of the top level of code if some of
437the modules are platform-specific. In that case, it may not even be possible to
438import all of the modules at the top of the file. In this case, importing the
439correct modules in the corresponding platform-specific code is a good option.
440
441Only move imports into a local scope, such as inside a function definition, if
442it's necessary to solve a problem such as avoiding a circular import or are
443trying to reduce the initialization time of a module. This technique is
444especially helpful if many of the imports are unnecessary depending on how the
445program executes. You may also want to move imports into a function if the
446modules are only ever used in that function. Note that loading a module the
447first time may be expensive because of the one time initialization of the
448module, but loading a module multiple times is virtually free, costing only a
449couple of dictionary lookups. Even if the module name has gone out of scope,
450the module is probably available in :data:`sys.modules`.
451
452If only instances of a specific class use a module, then it is reasonable to
453import the module in the class's ``__init__`` method and then assign the module
454to an instance variable so that the module is always available (via that
455instance variable) during the life of the object. Note that to delay an import
456until the class is instantiated, the import must be inside a method. Putting
457the import inside the class but outside of any method still causes the import to
458occur when the module is initialized.
459
460
461How can I pass optional or keyword parameters from one function to another?
462---------------------------------------------------------------------------
463
464Collect the arguments using the ``*`` and ``**`` specifiers in the function's
465parameter list; this gives you the positional arguments as a tuple and the
466keyword arguments as a dictionary. You can then pass these arguments when
467calling another function by using ``*`` and ``**``::
468
469 def f(x, *args, **kwargs):
470 ...
471 kwargs['width'] = '14.3c'
472 ...
473 g(x, *args, **kwargs)
474
475In the unlikely case that you care about Python versions older than 2.0, use
476:func:`apply`::
477
478 def f(x, *args, **kwargs):
479 ...
480 kwargs['width'] = '14.3c'
481 ...
482 apply(g, (x,)+args, kwargs)
483
484
485How do I write a function with output parameters (call by reference)?
486---------------------------------------------------------------------
487
488Remember that arguments are passed by assignment in Python. Since assignment
489just creates references to objects, there's no alias between an argument name in
490the caller and callee, and so no call-by-reference per se. You can achieve the
491desired effect in a number of ways.
492
4931) By returning a tuple of the results::
494
495 def func2(a, b):
496 a = 'new-value' # a and b are local names
497 b = b + 1 # assigned to new objects
498 return a, b # return new values
499
500 x, y = 'old-value', 99
501 x, y = func2(x, y)
502 print x, y # output: new-value 100
503
504 This is almost always the clearest solution.
505
5062) By using global variables. This isn't thread-safe, and is not recommended.
507
5083) By passing a mutable (changeable in-place) object::
509
510 def func1(a):
511 a[0] = 'new-value' # 'a' references a mutable list
512 a[1] = a[1] + 1 # changes a shared object
513
514 args = ['old-value', 99]
515 func1(args)
516 print args[0], args[1] # output: new-value 100
517
5184) By passing in a dictionary that gets mutated::
519
520 def func3(args):
521 args['a'] = 'new-value' # args is a mutable dictionary
522 args['b'] = args['b'] + 1 # change it in-place
523
524 args = {'a':' old-value', 'b': 99}
525 func3(args)
526 print args['a'], args['b']
527
5285) Or bundle up values in a class instance::
529
530 class callByRef:
531 def __init__(self, **args):
532 for (key, value) in args.items():
533 setattr(self, key, value)
534
535 def func4(args):
536 args.a = 'new-value' # args is a mutable callByRef
537 args.b = args.b + 1 # change object in-place
538
539 args = callByRef(a='old-value', b=99)
540 func4(args)
541 print args.a, args.b
542
543
544 There's almost never a good reason to get this complicated.
545
546Your best choice is to return a tuple containing the multiple results.
547
548
549How do you make a higher order function in Python?
550--------------------------------------------------
551
552You have two choices: you can use nested scopes or you can use callable objects.
553For example, suppose you wanted to define ``linear(a,b)`` which returns a
554function ``f(x)`` that computes the value ``a*x+b``. Using nested scopes::
555
556 def linear(a, b):
557 def result(x):
558 return a * x + b
559 return result
560
561Or using a callable object::
562
563 class linear:
564
565 def __init__(self, a, b):
566 self.a, self.b = a, b
567
568 def __call__(self, x):
569 return self.a * x + self.b
570
571In both cases, ::
572
573 taxes = linear(0.3, 2)
574
575gives a callable object where ``taxes(10e6) == 0.3 * 10e6 + 2``.
576
577The callable object approach has the disadvantage that it is a bit slower and
578results in slightly longer code. However, note that a collection of callables
579can share their signature via inheritance::
580
581 class exponential(linear):
582 # __init__ inherited
583 def __call__(self, x):
584 return self.a * (x ** self.b)
585
586Object can encapsulate state for several methods::
587
588 class counter:
589
590 value = 0
591
592 def set(self, x):
593 self.value = x
594
595 def up(self):
596 self.value = self.value + 1
597
598 def down(self):
599 self.value = self.value - 1
600
601 count = counter()
602 inc, dec, reset = count.up, count.down, count.set
603
604Here ``inc()``, ``dec()`` and ``reset()`` act like functions which share the
605same counting variable.
606
607
608How do I copy an object in Python?
609----------------------------------
610
611In general, try :func:`copy.copy` or :func:`copy.deepcopy` for the general case.
612Not all objects can be copied, but most can.
613
614Some objects can be copied more easily. Dictionaries have a :meth:`~dict.copy`
615method::
616
617 newdict = olddict.copy()
618
619Sequences can be copied by slicing::
620
621 new_l = l[:]
622
623
624How can I find the methods or attributes of an object?
625------------------------------------------------------
626
627For an instance x of a user-defined class, ``dir(x)`` returns an alphabetized
628list of the names containing the instance attributes and methods and attributes
629defined by its class.
630
631
632How can my code discover the name of an object?
633-----------------------------------------------
634
635Generally speaking, it can't, because objects don't really have names.
636Essentially, assignment always binds a name to a value; The same is true of
637``def`` and ``class`` statements, but in that case the value is a
638callable. Consider the following code::
639
640 class A:
641 pass
642
643 B = A
644
645 a = B()
646 b = a
647 print b
648 <__main__.A instance at 016D07CC>
649 print a
650 <__main__.A instance at 016D07CC>
651
652Arguably the class has a name: even though it is bound to two names and invoked
653through the name B the created instance is still reported as an instance of
654class A. However, it is impossible to say whether the instance's name is a or
655b, since both names are bound to the same value.
656
657Generally speaking it should not be necessary for your code to "know the names"
658of particular values. Unless you are deliberately writing introspective
659programs, this is usually an indication that a change of approach might be
660beneficial.
661
662In comp.lang.python, Fredrik Lundh once gave an excellent analogy in answer to
663this question:
664
665 The same way as you get the name of that cat you found on your porch: the cat
666 (object) itself cannot tell you its name, and it doesn't really care -- so
667 the only way to find out what it's called is to ask all your neighbours
668 (namespaces) if it's their cat (object)...
669
670 ....and don't be surprised if you'll find that it's known by many names, or
671 no name at all!
672
673
674What's up with the comma operator's precedence?
675-----------------------------------------------
676
677Comma is not an operator in Python. Consider this session::
678
679 >>> "a" in "b", "a"
680 (False, '1')
681
682Since the comma is not an operator, but a separator between expressions the
683above is evaluated as if you had entered::
684
685 >>> ("a" in "b"), "a"
686
687not::
688
689 >>> "a" in ("5", "a")
690
691The same is true of the various assignment operators (``=``, ``+=`` etc). They
692are not truly operators but syntactic delimiters in assignment statements.
693
694
695Is there an equivalent of C's "?:" ternary operator?
696----------------------------------------------------
697
698Yes, this feature was added in Python 2.5. The syntax would be as follows::
699
700 [on_true] if [expression] else [on_false]
701
702 x, y = 50, 25
703
704 small = x if x < y else y
705
706For versions previous to 2.5 the answer would be 'No'.
707
708.. XXX remove rest?
709
710In many cases you can mimic ``a ? b : c`` with ``a and b or c``, but there's a
711flaw: if *b* is zero (or empty, or ``None`` -- anything that tests false) then
712*c* will be selected instead. In many cases you can prove by looking at the
713code that this can't happen (e.g. because *b* is a constant or has a type that
714can never be false), but in general this can be a problem.
715
716Tim Peters (who wishes it was Steve Majewski) suggested the following solution:
717``(a and [b] or [c])[0]``. Because ``[b]`` is a singleton list it is never
718false, so the wrong path is never taken; then applying ``[0]`` to the whole
719thing gets the *b* or *c* that you really wanted. Ugly, but it gets you there
720in the rare cases where it is really inconvenient to rewrite your code using
721'if'.
722
723The best course is usually to write a simple ``if...else`` statement. Another
724solution is to implement the ``?:`` operator as a function::
725
726 def q(cond, on_true, on_false):
727 if cond:
728 if not isfunction(on_true):
729 return on_true
730 else:
731 return apply(on_true)
732 else:
733 if not isfunction(on_false):
734 return on_false
735 else:
736 return apply(on_false)
737
738In most cases you'll pass b and c directly: ``q(a, b, c)``. To avoid evaluating
739b or c when they shouldn't be, encapsulate them within a lambda function, e.g.:
740``q(a, lambda: b, lambda: c)``.
741
742It has been asked *why* Python has no if-then-else expression. There are
743several answers: many languages do just fine without one; it can easily lead to
744less readable code; no sufficiently "Pythonic" syntax has been discovered; a
745search of the standard library found remarkably few places where using an
746if-then-else expression would make the code more understandable.
747
748In 2002, :pep:`308` was written proposing several possible syntaxes and the
749community was asked to vote on the issue. The vote was inconclusive. Most
750people liked one of the syntaxes, but also hated other syntaxes; many votes
751implied that people preferred no ternary operator rather than having a syntax
752they hated.
753
754
755Is it possible to write obfuscated one-liners in Python?
756--------------------------------------------------------
757
758Yes. Usually this is done by nesting :keyword:`lambda` within
759:keyword:`lambda`. See the following three examples, due to Ulf Bartelt::
760
761 # Primes < 1000
762 print filter(None,map(lambda y:y*reduce(lambda x,y:x*y!=0,
763 map(lambda x,y=y:y%x,range(2,int(pow(y,0.5)+1))),1),range(2,1000)))
764
765 # First 10 Fibonacci numbers
766 print map(lambda x,f=lambda x,f:(x<=1) or (f(x-1,f)+f(x-2,f)): f(x,f),
767 range(10))
768
769 # Mandelbrot set
770 print (lambda Ru,Ro,Iu,Io,IM,Sx,Sy:reduce(lambda x,y:x+y,map(lambda y,
771 Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,Sy=Sy,L=lambda yc,Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,i=IM,
772 Sx=Sx,Sy=Sy:reduce(lambda x,y:x+y,map(lambda x,xc=Ru,yc=yc,Ru=Ru,Ro=Ro,
773 i=i,Sx=Sx,F=lambda xc,yc,x,y,k,f=lambda xc,yc,x,y,k,f:(k<=0)or (x*x+y*y
774 >=4.0) or 1+f(xc,yc,x*x-y*y+xc,2.0*x*y+yc,k-1,f):f(xc,yc,x,y,k,f):chr(
775 64+F(Ru+x*(Ro-Ru)/Sx,yc,0,0,i)),range(Sx))):L(Iu+y*(Io-Iu)/Sy),range(Sy
776 ))))(-2.1, 0.7, -1.2, 1.2, 30, 80, 24)
777 # \___ ___/ \___ ___/ | | |__ lines on screen
778 # V V | |______ columns on screen
779 # | | |__________ maximum of "iterations"
780 # | |_________________ range on y axis
781 # |____________________________ range on x axis
782
783Don't try this at home, kids!
784
785
786Numbers and strings
787===================
788
789How do I specify hexadecimal and octal integers?
790------------------------------------------------
791
792To specify an octal digit, precede the octal value with a zero. For example, to
793set the variable "a" to the octal value "10" (8 in decimal), type::
794
795 >>> a = 010
796 >>> a
797 8
798
799Hexadecimal is just as easy. Simply precede the hexadecimal number with a zero,
800and then a lower or uppercase "x". Hexadecimal digits can be specified in lower
801or uppercase. For example, in the Python interpreter::
802
803 >>> a = 0xa5
804 >>> a
805 165
806 >>> b = 0XB2
807 >>> b
808 178
809
810
811Why does -22 / 10 return -3?
812----------------------------
813
814It's primarily driven by the desire that ``i % j`` have the same sign as ``j``.
815If you want that, and also want::
816
817 i == (i / j) * j + (i % j)
818
819then integer division has to return the floor. C also requires that identity to
820hold, and then compilers that truncate ``i / j`` need to make ``i % j`` have the
821same sign as ``i``.
822
823There are few real use cases for ``i % j`` when ``j`` is negative. When ``j``
824is positive, there are many, and in virtually all of them it's more useful for
825``i % j`` to be ``>= 0``. If the clock says 10 now, what did it say 200 hours
826ago? ``-190 % 12 == 2`` is useful; ``-190 % 12 == -10`` is a bug waiting to
827bite.
828
829
830How do I convert a string to a number?
831--------------------------------------
832
833For integers, use the built-in :func:`int` type constructor, e.g. ``int('144')
834== 144``. Similarly, :func:`float` converts to floating-point,
835e.g. ``float('144') == 144.0``.
836
837By default, these interpret the number as decimal, so that ``int('0144') ==
838144`` and ``int('0x144')`` raises :exc:`ValueError`. ``int(string, base)`` takes
839the base to convert from as a second optional argument, so ``int('0x144', 16) ==
840324``. If the base is specified as 0, the number is interpreted using Python's
841rules: a leading '0' indicates octal, and '0x' indicates a hex number.
842
843Do not use the built-in function :func:`eval` if all you need is to convert
844strings to numbers. :func:`eval` will be significantly slower and it presents a
845security risk: someone could pass you a Python expression that might have
846unwanted side effects. For example, someone could pass
847``__import__('os').system("rm -rf $HOME")`` which would erase your home
848directory.
849
850:func:`eval` also has the effect of interpreting numbers as Python expressions,
851so that e.g. ``eval('09')`` gives a syntax error because Python regards numbers
852starting with '0' as octal (base 8).
853
854
855How do I convert a number to a string?
856--------------------------------------
857
858To convert, e.g., the number 144 to the string '144', use the built-in type
859constructor :func:`str`. If you want a hexadecimal or octal representation, use
860the built-in functions ``hex()`` or ``oct()``. For fancy formatting, use
861:ref:`the % operator <string-formatting>` on strings, e.g. ``"%04d" % 144``
862yields ``'0144'`` and ``"%.3f" % (1/3.0)`` yields ``'0.333'``. See the library
863reference manual for details.
864
865
866How do I modify a string in place?
867----------------------------------
868
869You can't, because strings are immutable. If you need an object with this
870ability, try converting the string to a list or use the array module::
871
872 >>> s = "Hello, world"
873 >>> a = list(s)
874 >>> print a
875 ['H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd']
876 >>> a[7:] = list("there!")
877 >>> ''.join(a)
878 'Hello, there!'
879
880 >>> import array
881 >>> a = array.array('c', s)
882 >>> print a
883 array('c', 'Hello, world')
884 >>> a[0] = 'y' ; print a
885 array('c', 'yello world')
886 >>> a.tostring()
887 'yello, world'
888
889
890How do I use strings to call functions/methods?
891-----------------------------------------------
892
893There are various techniques.
894
895* The best is to use a dictionary that maps strings to functions. The primary
896 advantage of this technique is that the strings do not need to match the names
897 of the functions. This is also the primary technique used to emulate a case
898 construct::
899
900 def a():
901 pass
902
903 def b():
904 pass
905
906 dispatch = {'go': a, 'stop': b} # Note lack of parens for funcs
907
908 dispatch[get_input()]() # Note trailing parens to call function
909
910* Use the built-in function :func:`getattr`::
911
912 import foo
913 getattr(foo, 'bar')()
914
915 Note that :func:`getattr` works on any object, including classes, class
916 instances, modules, and so on.
917
918 This is used in several places in the standard library, like this::
919
920 class Foo:
921 def do_foo(self):
922 ...
923
924 def do_bar(self):
925 ...
926
927 f = getattr(foo_instance, 'do_' + opname)
928 f()
929
930
931* Use :func:`locals` or :func:`eval` to resolve the function name::
932
933 def myFunc():
934 print "hello"
935
936 fname = "myFunc"
937
938 f = locals()[fname]
939 f()
940
941 f = eval(fname)
942 f()
943
944 Note: Using :func:`eval` is slow and dangerous. If you don't have absolute
945 control over the contents of the string, someone could pass a string that
946 resulted in an arbitrary function being executed.
947
948Is there an equivalent to Perl's chomp() for removing trailing newlines from strings?
949-------------------------------------------------------------------------------------
950
951Starting with Python 2.2, you can use ``S.rstrip("\r\n")`` to remove all
952occurences of any line terminator from the end of the string ``S`` without
953removing other trailing whitespace. If the string ``S`` represents more than
954one line, with several empty lines at the end, the line terminators for all the
955blank lines will be removed::
956
957 >>> lines = ("line 1 \r\n"
958 ... "\r\n"
959 ... "\r\n")
960 >>> lines.rstrip("\n\r")
961 "line 1 "
962
963Since this is typically only desired when reading text one line at a time, using
964``S.rstrip()`` this way works well.
965
966For older versions of Python, There are two partial substitutes:
967
968- If you want to remove all trailing whitespace, use the ``rstrip()`` method of
969 string objects. This removes all trailing whitespace, not just a single
970 newline.
971
972- Otherwise, if there is only one line in the string ``S``, use
973 ``S.splitlines()[0]``.
974
975
976Is there a scanf() or sscanf() equivalent?
977------------------------------------------
978
979Not as such.
980
981For simple input parsing, the easiest approach is usually to split the line into
982whitespace-delimited words using the :meth:`~str.split` method of string objects
983and then convert decimal strings to numeric values using :func:`int` or
984:func:`float`. ``split()`` supports an optional "sep" parameter which is useful
985if the line uses something other than whitespace as a separator.
986
987For more complicated input parsing, regular expressions more powerful than C's
988:cfunc:`sscanf` and better suited for the task.
989
990
991What does 'UnicodeError: ASCII [decoding,encoding] error: ordinal not in range(128)' mean?
992------------------------------------------------------------------------------------------
993
994This error indicates that your Python installation can handle only 7-bit ASCII
995strings. There are a couple ways to fix or work around the problem.
996
997If your programs must handle data in arbitrary character set encodings, the
998environment the application runs in will generally identify the encoding of the
999data it is handing you. You need to convert the input to Unicode data using
1000that encoding. For example, a program that handles email or web input will
1001typically find character set encoding information in Content-Type headers. This
1002can then be used to properly convert input data to Unicode. Assuming the string
1003referred to by ``value`` is encoded as UTF-8::
1004
1005 value = unicode(value, "utf-8")
1006
1007will return a Unicode object. If the data is not correctly encoded as UTF-8,
1008the above call will raise a :exc:`UnicodeError` exception.
1009
1010If you only want strings converted to Unicode which have non-ASCII data, you can
1011try converting them first assuming an ASCII encoding, and then generate Unicode
1012objects if that fails::
1013
1014 try:
1015 x = unicode(value, "ascii")
1016 except UnicodeError:
1017 value = unicode(value, "utf-8")
1018 else:
1019 # value was valid ASCII data
1020 pass
1021
1022It's possible to set a default encoding in a file called ``sitecustomize.py``
1023that's part of the Python library. However, this isn't recommended because
1024changing the Python-wide default encoding may cause third-party extension
1025modules to fail.
1026
1027Note that on Windows, there is an encoding known as "mbcs", which uses an
1028encoding specific to your current locale. In many cases, and particularly when
1029working with COM, this may be an appropriate default encoding to use.
1030
1031
1032Sequences (Tuples/Lists)
1033========================
1034
1035How do I convert between tuples and lists?
1036------------------------------------------
1037
1038The type constructor ``tuple(seq)`` converts any sequence (actually, any
1039iterable) into a tuple with the same items in the same order.
1040
1041For example, ``tuple([1, 2, 3])`` yields ``(1, 2, 3)`` and ``tuple('abc')``
1042yields ``('a', 'b', 'c')``. If the argument is a tuple, it does not make a copy
1043but returns the same object, so it is cheap to call :func:`tuple` when you
1044aren't sure that an object is already a tuple.
1045
1046The type constructor ``list(seq)`` converts any sequence or iterable into a list
1047with the same items in the same order. For example, ``list((1, 2, 3))`` yields
1048``[1, 2, 3]`` and ``list('abc')`` yields ``['a', 'b', 'c']``. If the argument
1049is a list, it makes a copy just like ``seq[:]`` would.
1050
1051
1052What's a negative index?
1053------------------------
1054
1055Python sequences are indexed with positive numbers and negative numbers. For
1056positive numbers 0 is the first index 1 is the second index and so forth. For
1057negative indices -1 is the last index and -2 is the penultimate (next to last)
1058index and so forth. Think of ``seq[-n]`` as the same as ``seq[len(seq)-n]``.
1059
1060Using negative indices can be very convenient. For example ``S[:-1]`` is all of
1061the string except for its last character, which is useful for removing the
1062trailing newline from a string.
1063
1064
1065How do I iterate over a sequence in reverse order?
1066--------------------------------------------------
1067
1068Use the :func:`reversed` builtin function, which is new in Python 2.4::
1069
1070 for x in reversed(sequence):
1071 ... # do something with x...
1072
1073This won't touch your original sequence, but build a new copy with reversed
1074order to iterate over.
1075
1076With Python 2.3, you can use an extended slice syntax::
1077
1078 for x in sequence[::-1]:
1079 ... # do something with x...
1080
1081
1082How do you remove duplicates from a list?
1083-----------------------------------------
1084
1085See the Python Cookbook for a long discussion of many ways to do this:
1086
1087 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52560
1088
1089If you don't mind reordering the list, sort it and then scan from the end of the
1090list, deleting duplicates as you go::
1091
1092 if List:
1093 List.sort()
1094 last = List[-1]
1095 for i in range(len(List)-2, -1, -1):
1096 if last == List[i]:
1097 del List[i]
1098 else:
1099 last = List[i]
1100
1101If all elements of the list may be used as dictionary keys (i.e. they are all
1102hashable) this is often faster ::
1103
1104 d = {}
1105 for x in List:
1106 d[x] = x
1107 List = d.values()
1108
1109In Python 2.5 and later, the following is possible instead::
1110
1111 List = list(set(List))
1112
1113This converts the list into a set, thereby removing duplicates, and then back
1114into a list.
1115
1116
1117How do you make an array in Python?
1118-----------------------------------
1119
1120Use a list::
1121
1122 ["this", 1, "is", "an", "array"]
1123
1124Lists are equivalent to C or Pascal arrays in their time complexity; the primary
1125difference is that a Python list can contain objects of many different types.
1126
1127The ``array`` module also provides methods for creating arrays of fixed types
1128with compact representations, but they are slower to index than lists. Also
1129note that the Numeric extensions and others define array-like structures with
1130various characteristics as well.
1131
1132To get Lisp-style linked lists, you can emulate cons cells using tuples::
1133
1134 lisp_list = ("like", ("this", ("example", None) ) )
1135
1136If mutability is desired, you could use lists instead of tuples. Here the
1137analogue of lisp car is ``lisp_list[0]`` and the analogue of cdr is
1138``lisp_list[1]``. Only do this if you're sure you really need to, because it's
1139usually a lot slower than using Python lists.
1140
1141
1142How do I create a multidimensional list?
1143----------------------------------------
1144
1145You probably tried to make a multidimensional array like this::
1146
1147 A = [[None] * 2] * 3
1148
1149This looks correct if you print it::
1150
1151 >>> A
1152 [[None, None], [None, None], [None, None]]
1153
1154But when you assign a value, it shows up in multiple places:
1155
1156 >>> A[0][0] = 5
1157 >>> A
1158 [[5, None], [5, None], [5, None]]
1159
1160The reason is that replicating a list with ``*`` doesn't create copies, it only
1161creates references to the existing objects. The ``*3`` creates a list
1162containing 3 references to the same list of length two. Changes to one row will
1163show in all rows, which is almost certainly not what you want.
1164
1165The suggested approach is to create a list of the desired length first and then
1166fill in each element with a newly created list::
1167
1168 A = [None] * 3
1169 for i in range(3):
1170 A[i] = [None] * 2
1171
1172This generates a list containing 3 different lists of length two. You can also
1173use a list comprehension::
1174
1175 w, h = 2, 3
1176 A = [[None] * w for i in range(h)]
1177
1178Or, you can use an extension that provides a matrix datatype; `Numeric Python
Georg Brandl495f7b52009-10-27 15:28:25 +00001179<http://numpy.scipy.org/>`_ is the best known.
Georg Brandld7413152009-10-11 21:25:26 +00001180
1181
1182How do I apply a method to a sequence of objects?
1183-------------------------------------------------
1184
1185Use a list comprehension::
1186
1187 result = [obj.method() for obj in List]
1188
1189More generically, you can try the following function::
1190
1191 def method_map(objects, method, arguments):
1192 """method_map([a,b], "meth", (1,2)) gives [a.meth(1,2), b.meth(1,2)]"""
1193 nobjects = len(objects)
1194 methods = map(getattr, objects, [method]*nobjects)
1195 return map(apply, methods, [arguments]*nobjects)
1196
1197
1198Dictionaries
1199============
1200
1201How can I get a dictionary to display its keys in a consistent order?
1202---------------------------------------------------------------------
1203
1204You can't. Dictionaries store their keys in an unpredictable order, so the
1205display order of a dictionary's elements will be similarly unpredictable.
1206
1207This can be frustrating if you want to save a printable version to a file, make
1208some changes and then compare it with some other printed dictionary. In this
1209case, use the ``pprint`` module to pretty-print the dictionary; the items will
1210be presented in order sorted by the key.
1211
1212A more complicated solution is to subclass ``UserDict.UserDict`` to create a
1213``SortedDict`` class that prints itself in a predictable order. Here's one
1214simpleminded implementation of such a class::
1215
1216 import UserDict, string
1217
1218 class SortedDict(UserDict.UserDict):
1219 def __repr__(self):
1220 result = []
1221 append = result.append
1222 keys = self.data.keys()
1223 keys.sort()
1224 for k in keys:
1225 append("%s: %s" % (`k`, `self.data[k]`))
1226 return "{%s}" % string.join(result, ", ")
1227
1228 __str__ = __repr__
1229
1230This will work for many common situations you might encounter, though it's far
1231from a perfect solution. The largest flaw is that if some values in the
1232dictionary are also dictionaries, their values won't be presented in any
1233particular order.
1234
1235
1236I want to do a complicated sort: can you do a Schwartzian Transform in Python?
1237------------------------------------------------------------------------------
1238
1239The technique, attributed to Randal Schwartz of the Perl community, sorts the
1240elements of a list by a metric which maps each element to its "sort value". In
1241Python, just use the ``key`` argument for the ``sort()`` method::
1242
1243 Isorted = L[:]
1244 Isorted.sort(key=lambda s: int(s[10:15]))
1245
1246The ``key`` argument is new in Python 2.4, for older versions this kind of
1247sorting is quite simple to do with list comprehensions. To sort a list of
1248strings by their uppercase values::
1249
1250 tmp1 = [(x.upper(), x) for x in L] # Schwartzian transform
1251 tmp1.sort()
1252 Usorted = [x[1] for x in tmp1]
1253
1254To sort by the integer value of a subfield extending from positions 10-15 in
1255each string::
1256
1257 tmp2 = [(int(s[10:15]), s) for s in L] # Schwartzian transform
1258 tmp2.sort()
1259 Isorted = [x[1] for x in tmp2]
1260
1261Note that Isorted may also be computed by ::
1262
1263 def intfield(s):
1264 return int(s[10:15])
1265
1266 def Icmp(s1, s2):
1267 return cmp(intfield(s1), intfield(s2))
1268
1269 Isorted = L[:]
1270 Isorted.sort(Icmp)
1271
1272but since this method calls ``intfield()`` many times for each element of L, it
1273is slower than the Schwartzian Transform.
1274
1275
1276How can I sort one list by values from another list?
1277----------------------------------------------------
1278
1279Merge them into a single list of tuples, sort the resulting list, and then pick
1280out the element you want. ::
1281
1282 >>> list1 = ["what", "I'm", "sorting", "by"]
1283 >>> list2 = ["something", "else", "to", "sort"]
1284 >>> pairs = zip(list1, list2)
1285 >>> pairs
1286 [('what', 'something'), ("I'm", 'else'), ('sorting', 'to'), ('by', 'sort')]
1287 >>> pairs.sort()
1288 >>> result = [ x[1] for x in pairs ]
1289 >>> result
1290 ['else', 'sort', 'to', 'something']
1291
1292An alternative for the last step is::
1293
1294 result = []
1295 for p in pairs: result.append(p[1])
1296
1297If you find this more legible, you might prefer to use this instead of the final
1298list comprehension. However, it is almost twice as slow for long lists. Why?
1299First, the ``append()`` operation has to reallocate memory, and while it uses
1300some tricks to avoid doing that each time, it still has to do it occasionally,
1301and that costs quite a bit. Second, the expression "result.append" requires an
1302extra attribute lookup, and third, there's a speed reduction from having to make
1303all those function calls.
1304
1305
1306Objects
1307=======
1308
1309What is a class?
1310----------------
1311
1312A class is the particular object type created by executing a class statement.
1313Class objects are used as templates to create instance objects, which embody
1314both the data (attributes) and code (methods) specific to a datatype.
1315
1316A class can be based on one or more other classes, called its base class(es). It
1317then inherits the attributes and methods of its base classes. This allows an
1318object model to be successively refined by inheritance. You might have a
1319generic ``Mailbox`` class that provides basic accessor methods for a mailbox,
1320and subclasses such as ``MboxMailbox``, ``MaildirMailbox``, ``OutlookMailbox``
1321that handle various specific mailbox formats.
1322
1323
1324What is a method?
1325-----------------
1326
1327A method is a function on some object ``x`` that you normally call as
1328``x.name(arguments...)``. Methods are defined as functions inside the class
1329definition::
1330
1331 class C:
1332 def meth (self, arg):
1333 return arg * 2 + self.attribute
1334
1335
1336What is self?
1337-------------
1338
1339Self is merely a conventional name for the first argument of a method. A method
1340defined as ``meth(self, a, b, c)`` should be called as ``x.meth(a, b, c)`` for
1341some instance ``x`` of the class in which the definition occurs; the called
1342method will think it is called as ``meth(x, a, b, c)``.
1343
1344See also :ref:`why-self`.
1345
1346
1347How do I check if an object is an instance of a given class or of a subclass of it?
1348-----------------------------------------------------------------------------------
1349
1350Use the built-in function ``isinstance(obj, cls)``. You can check if an object
1351is an instance of any of a number of classes by providing a tuple instead of a
1352single class, e.g. ``isinstance(obj, (class1, class2, ...))``, and can also
1353check whether an object is one of Python's built-in types, e.g.
1354``isinstance(obj, str)`` or ``isinstance(obj, (int, long, float, complex))``.
1355
1356Note that most programs do not use :func:`isinstance` on user-defined classes
1357very often. If you are developing the classes yourself, a more proper
1358object-oriented style is to define methods on the classes that encapsulate a
1359particular behaviour, instead of checking the object's class and doing a
1360different thing based on what class it is. For example, if you have a function
1361that does something::
1362
1363 def search (obj):
1364 if isinstance(obj, Mailbox):
1365 # ... code to search a mailbox
1366 elif isinstance(obj, Document):
1367 # ... code to search a document
1368 elif ...
1369
1370A better approach is to define a ``search()`` method on all the classes and just
1371call it::
1372
1373 class Mailbox:
1374 def search(self):
1375 # ... code to search a mailbox
1376
1377 class Document:
1378 def search(self):
1379 # ... code to search a document
1380
1381 obj.search()
1382
1383
1384What is delegation?
1385-------------------
1386
1387Delegation is an object oriented technique (also called a design pattern).
1388Let's say you have an object ``x`` and want to change the behaviour of just one
1389of its methods. You can create a new class that provides a new implementation
1390of the method you're interested in changing and delegates all other methods to
1391the corresponding method of ``x``.
1392
1393Python programmers can easily implement delegation. For example, the following
1394class implements a class that behaves like a file but converts all written data
1395to uppercase::
1396
1397 class UpperOut:
1398
1399 def __init__(self, outfile):
1400 self._outfile = outfile
1401
1402 def write(self, s):
1403 self._outfile.write(s.upper())
1404
1405 def __getattr__(self, name):
1406 return getattr(self._outfile, name)
1407
1408Here the ``UpperOut`` class redefines the ``write()`` method to convert the
1409argument string to uppercase before calling the underlying
1410``self.__outfile.write()`` method. All other methods are delegated to the
1411underlying ``self.__outfile`` object. The delegation is accomplished via the
1412``__getattr__`` method; consult :ref:`the language reference <attribute-access>`
1413for more information about controlling attribute access.
1414
1415Note that for more general cases delegation can get trickier. When attributes
1416must be set as well as retrieved, the class must define a :meth:`__setattr__`
1417method too, and it must do so carefully. The basic implementation of
1418:meth:`__setattr__` is roughly equivalent to the following::
1419
1420 class X:
1421 ...
1422 def __setattr__(self, name, value):
1423 self.__dict__[name] = value
1424 ...
1425
1426Most :meth:`__setattr__` implementations must modify ``self.__dict__`` to store
1427local state for self without causing an infinite recursion.
1428
1429
1430How do I call a method defined in a base class from a derived class that overrides it?
1431--------------------------------------------------------------------------------------
1432
1433If you're using new-style classes, use the built-in :func:`super` function::
1434
1435 class Derived(Base):
1436 def meth (self):
1437 super(Derived, self).meth()
1438
1439If you're using classic classes: For a class definition such as ``class
1440Derived(Base): ...`` you can call method ``meth()`` defined in ``Base`` (or one
1441of ``Base``'s base classes) as ``Base.meth(self, arguments...)``. Here,
1442``Base.meth`` is an unbound method, so you need to provide the ``self``
1443argument.
1444
1445
1446How can I organize my code to make it easier to change the base class?
1447----------------------------------------------------------------------
1448
1449You could define an alias for the base class, assign the real base class to it
1450before your class definition, and use the alias throughout your class. Then all
1451you have to change is the value assigned to the alias. Incidentally, this trick
1452is also handy if you want to decide dynamically (e.g. depending on availability
1453of resources) which base class to use. Example::
1454
1455 BaseAlias = <real base class>
1456
1457 class Derived(BaseAlias):
1458 def meth(self):
1459 BaseAlias.meth(self)
1460 ...
1461
1462
1463How do I create static class data and static class methods?
1464-----------------------------------------------------------
1465
1466Static data (in the sense of C++ or Java) is easy; static methods (again in the
1467sense of C++ or Java) are not supported directly.
1468
1469For static data, simply define a class attribute. To assign a new value to the
1470attribute, you have to explicitly use the class name in the assignment::
1471
1472 class C:
1473 count = 0 # number of times C.__init__ called
1474
1475 def __init__(self):
1476 C.count = C.count + 1
1477
1478 def getcount(self):
1479 return C.count # or return self.count
1480
1481``c.count`` also refers to ``C.count`` for any ``c`` such that ``isinstance(c,
1482C)`` holds, unless overridden by ``c`` itself or by some class on the base-class
1483search path from ``c.__class__`` back to ``C``.
1484
1485Caution: within a method of C, an assignment like ``self.count = 42`` creates a
1486new and unrelated instance vrbl named "count" in ``self``'s own dict. Rebinding
1487of a class-static data name must always specify the class whether inside a
1488method or not::
1489
1490 C.count = 314
1491
1492Static methods are possible since Python 2.2::
1493
1494 class C:
1495 def static(arg1, arg2, arg3):
1496 # No 'self' parameter!
1497 ...
1498 static = staticmethod(static)
1499
1500With Python 2.4's decorators, this can also be written as ::
1501
1502 class C:
1503 @staticmethod
1504 def static(arg1, arg2, arg3):
1505 # No 'self' parameter!
1506 ...
1507
1508However, a far more straightforward way to get the effect of a static method is
1509via a simple module-level function::
1510
1511 def getcount():
1512 return C.count
1513
1514If your code is structured so as to define one class (or tightly related class
1515hierarchy) per module, this supplies the desired encapsulation.
1516
1517
1518How can I overload constructors (or methods) in Python?
1519-------------------------------------------------------
1520
1521This answer actually applies to all methods, but the question usually comes up
1522first in the context of constructors.
1523
1524In C++ you'd write
1525
1526.. code-block:: c
1527
1528 class C {
1529 C() { cout << "No arguments\n"; }
1530 C(int i) { cout << "Argument is " << i << "\n"; }
1531 }
1532
1533In Python you have to write a single constructor that catches all cases using
1534default arguments. For example::
1535
1536 class C:
1537 def __init__(self, i=None):
1538 if i is None:
1539 print "No arguments"
1540 else:
1541 print "Argument is", i
1542
1543This is not entirely equivalent, but close enough in practice.
1544
1545You could also try a variable-length argument list, e.g. ::
1546
1547 def __init__(self, *args):
1548 ...
1549
1550The same approach works for all method definitions.
1551
1552
1553I try to use __spam and I get an error about _SomeClassName__spam.
1554------------------------------------------------------------------
1555
1556Variable names with double leading underscores are "mangled" to provide a simple
1557but effective way to define class private variables. Any identifier of the form
1558``__spam`` (at least two leading underscores, at most one trailing underscore)
1559is textually replaced with ``_classname__spam``, where ``classname`` is the
1560current class name with any leading underscores stripped.
1561
1562This doesn't guarantee privacy: an outside user can still deliberately access
1563the "_classname__spam" attribute, and private values are visible in the object's
1564``__dict__``. Many Python programmers never bother to use private variable
1565names at all.
1566
1567
1568My class defines __del__ but it is not called when I delete the object.
1569-----------------------------------------------------------------------
1570
1571There are several possible reasons for this.
1572
1573The del statement does not necessarily call :meth:`__del__` -- it simply
1574decrements the object's reference count, and if this reaches zero
1575:meth:`__del__` is called.
1576
1577If your data structures contain circular links (e.g. a tree where each child has
1578a parent reference and each parent has a list of children) the reference counts
1579will never go back to zero. Once in a while Python runs an algorithm to detect
1580such cycles, but the garbage collector might run some time after the last
1581reference to your data structure vanishes, so your :meth:`__del__` method may be
1582called at an inconvenient and random time. This is inconvenient if you're trying
1583to reproduce a problem. Worse, the order in which object's :meth:`__del__`
1584methods are executed is arbitrary. You can run :func:`gc.collect` to force a
1585collection, but there *are* pathological cases where objects will never be
1586collected.
1587
1588Despite the cycle collector, it's still a good idea to define an explicit
1589``close()`` method on objects to be called whenever you're done with them. The
1590``close()`` method can then remove attributes that refer to subobjecs. Don't
1591call :meth:`__del__` directly -- :meth:`__del__` should call ``close()`` and
1592``close()`` should make sure that it can be called more than once for the same
1593object.
1594
1595Another way to avoid cyclical references is to use the :mod:`weakref` module,
1596which allows you to point to objects without incrementing their reference count.
1597Tree data structures, for instance, should use weak references for their parent
1598and sibling references (if they need them!).
1599
1600If the object has ever been a local variable in a function that caught an
1601expression in an except clause, chances are that a reference to the object still
1602exists in that function's stack frame as contained in the stack trace.
1603Normally, calling :func:`sys.exc_clear` will take care of this by clearing the
1604last recorded exception.
1605
1606Finally, if your :meth:`__del__` method raises an exception, a warning message
1607is printed to :data:`sys.stderr`.
1608
1609
1610How do I get a list of all instances of a given class?
1611------------------------------------------------------
1612
1613Python does not keep track of all instances of a class (or of a built-in type).
1614You can program the class's constructor to keep track of all instances by
1615keeping a list of weak references to each instance.
1616
1617
1618Modules
1619=======
1620
1621How do I create a .pyc file?
1622----------------------------
1623
1624When a module is imported for the first time (or when the source is more recent
1625than the current compiled file) a ``.pyc`` file containing the compiled code
1626should be created in the same directory as the ``.py`` file.
1627
1628One reason that a ``.pyc`` file may not be created is permissions problems with
1629the directory. This can happen, for example, if you develop as one user but run
1630as another, such as if you are testing with a web server. Creation of a .pyc
1631file is automatic if you're importing a module and Python has the ability
1632(permissions, free space, etc...) to write the compiled module back to the
1633directory.
1634
1635Running Python on a top level script is not considered an import and no ``.pyc``
1636will be created. For example, if you have a top-level module ``abc.py`` that
1637imports another module ``xyz.py``, when you run abc, ``xyz.pyc`` will be created
1638since xyz is imported, but no ``abc.pyc`` file will be created since ``abc.py``
1639isn't being imported.
1640
1641If you need to create abc.pyc -- that is, to create a .pyc file for a module
1642that is not imported -- you can, using the :mod:`py_compile` and
1643:mod:`compileall` modules.
1644
1645The :mod:`py_compile` module can manually compile any module. One way is to use
1646the ``compile()`` function in that module interactively::
1647
1648 >>> import py_compile
1649 >>> py_compile.compile('abc.py')
1650
1651This will write the ``.pyc`` to the same location as ``abc.py`` (or you can
1652override that with the optional parameter ``cfile``).
1653
1654You can also automatically compile all files in a directory or directories using
1655the :mod:`compileall` module. You can do it from the shell prompt by running
1656``compileall.py`` and providing the path of a directory containing Python files
1657to compile::
1658
1659 python -m compileall .
1660
1661
1662How do I find the current module name?
1663--------------------------------------
1664
1665A module can find out its own module name by looking at the predefined global
1666variable ``__name__``. If this has the value ``'__main__'``, the program is
1667running as a script. Many modules that are usually used by importing them also
1668provide a command-line interface or a self-test, and only execute this code
1669after checking ``__name__``::
1670
1671 def main():
1672 print 'Running test...'
1673 ...
1674
1675 if __name__ == '__main__':
1676 main()
1677
1678
1679How can I have modules that mutually import each other?
1680-------------------------------------------------------
1681
1682Suppose you have the following modules:
1683
1684foo.py::
1685
1686 from bar import bar_var
1687 foo_var = 1
1688
1689bar.py::
1690
1691 from foo import foo_var
1692 bar_var = 2
1693
1694The problem is that the interpreter will perform the following steps:
1695
1696* main imports foo
1697* Empty globals for foo are created
1698* foo is compiled and starts executing
1699* foo imports bar
1700* Empty globals for bar are created
1701* bar is compiled and starts executing
1702* bar imports foo (which is a no-op since there already is a module named foo)
1703* bar.foo_var = foo.foo_var
1704
1705The last step fails, because Python isn't done with interpreting ``foo`` yet and
1706the global symbol dictionary for ``foo`` is still empty.
1707
1708The same thing happens when you use ``import foo``, and then try to access
1709``foo.foo_var`` in global code.
1710
1711There are (at least) three possible workarounds for this problem.
1712
1713Guido van Rossum recommends avoiding all uses of ``from <module> import ...``,
1714and placing all code inside functions. Initializations of global variables and
1715class variables should use constants or built-in functions only. This means
1716everything from an imported module is referenced as ``<module>.<name>``.
1717
1718Jim Roskind suggests performing steps in the following order in each module:
1719
1720* exports (globals, functions, and classes that don't need imported base
1721 classes)
1722* ``import`` statements
1723* active code (including globals that are initialized from imported values).
1724
1725van Rossum doesn't like this approach much because the imports appear in a
1726strange place, but it does work.
1727
1728Matthias Urlichs recommends restructuring your code so that the recursive import
1729is not necessary in the first place.
1730
1731These solutions are not mutually exclusive.
1732
1733
1734__import__('x.y.z') returns <module 'x'>; how do I get z?
1735---------------------------------------------------------
1736
1737Try::
1738
1739 __import__('x.y.z').y.z
1740
1741For more realistic situations, you may have to do something like ::
1742
1743 m = __import__(s)
1744 for i in s.split(".")[1:]:
1745 m = getattr(m, i)
1746
1747See :mod:`importlib` for a convenience function called
1748:func:`~importlib.import_module`.
1749
1750
1751
1752When I edit an imported module and reimport it, the changes don't show up. Why does this happen?
1753-------------------------------------------------------------------------------------------------
1754
1755For reasons of efficiency as well as consistency, Python only reads the module
1756file on the first time a module is imported. If it didn't, in a program
1757consisting of many modules where each one imports the same basic module, the
1758basic module would be parsed and re-parsed many times. To force rereading of a
1759changed module, do this::
1760
1761 import modname
1762 reload(modname)
1763
1764Warning: this technique is not 100% fool-proof. In particular, modules
1765containing statements like ::
1766
1767 from modname import some_objects
1768
1769will continue to work with the old version of the imported objects. If the
1770module contains class definitions, existing class instances will *not* be
1771updated to use the new class definition. This can result in the following
1772paradoxical behaviour:
1773
1774 >>> import cls
1775 >>> c = cls.C() # Create an instance of C
1776 >>> reload(cls)
1777 <module 'cls' from 'cls.pyc'>
1778 >>> isinstance(c, cls.C) # isinstance is false?!?
1779 False
1780
1781The nature of the problem is made clear if you print out the class objects:
1782
1783 >>> c.__class__
1784 <class cls.C at 0x7352a0>
1785 >>> cls.C
1786 <class cls.C at 0x4198d0>
1787