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