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