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