blob: f157a943a43816c36ea008aaea665da40debb895 [file] [log] [blame]
Georg Brandld7413152009-10-11 21:25:26 +00001:tocdepth: 2
2
3===============
4Programming FAQ
5===============
6
7.. contents::
8
9General Questions
10=================
11
12Is there a source code level debugger with breakpoints, single-stepping, etc.?
13------------------------------------------------------------------------------
14
15Yes.
16
17The pdb module is a simple but adequate console-mode debugger for Python. It is
18part of the standard Python library, and is :mod:`documented in the Library
19Reference Manual <pdb>`. You can also write your own debugger by using the code
20for pdb as an example.
21
22The IDLE interactive development environment, which is part of the standard
23Python distribution (normally available as Tools/scripts/idle), includes a
24graphical debugger. There is documentation for the IDLE debugger at
25http://www.python.org/idle/doc/idle2.html#Debugger.
26
27PythonWin is a Python IDE that includes a GUI debugger based on pdb. The
28Pythonwin debugger colors breakpoints and has quite a few cool features such as
29debugging non-Pythonwin programs. Pythonwin is available as part of the `Python
30for Windows Extensions <http://sourceforge.net/projects/pywin32/>`__ project and
31as a part of the ActivePython distribution (see
32http://www.activestate.com/Products/ActivePython/index.html).
33
34`Boa Constructor <http://boa-constructor.sourceforge.net/>`_ is an IDE and GUI
35builder that uses wxWidgets. It offers visual frame creation and manipulation,
36an object inspector, many views on the source like object browsers, inheritance
37hierarchies, doc string generated html documentation, an advanced debugger,
38integrated help, and Zope support.
39
40`Eric <http://www.die-offenbachs.de/eric/index.html>`_ is an IDE built on PyQt
41and the Scintilla editing component.
42
43Pydb is a version of the standard Python debugger pdb, modified for use with DDD
44(Data Display Debugger), a popular graphical debugger front end. Pydb can be
45found at http://bashdb.sourceforge.net/pydb/ and DDD can be found at
46http://www.gnu.org/software/ddd.
47
48There are a number of commercial Python IDEs that include graphical debuggers.
49They include:
50
51* Wing IDE (http://wingware.com/)
52* Komodo IDE (http://www.activestate.com/Products/Komodo)
53
54
55Is there a tool to help find bugs or perform static analysis?
56-------------------------------------------------------------
57
58Yes.
59
60PyChecker is a static analysis tool that finds bugs in Python source code and
61warns about code complexity and style. You can get PyChecker from
62http://pychecker.sf.net.
63
64`Pylint <http://www.logilab.org/projects/pylint>`_ is another tool that checks
65if a module satisfies a coding standard, and also makes it possible to write
66plug-ins to add a custom feature. In addition to the bug checking that
67PyChecker performs, Pylint offers some additional features such as checking line
68length, whether variable names are well-formed according to your coding
69standard, whether declared interfaces are fully implemented, and more.
Georg Brandl495f7b52009-10-27 15:28:25 +000070http://www.logilab.org/card/pylint_manual provides a full list of Pylint's
71features.
Georg Brandld7413152009-10-11 21:25:26 +000072
73
74How can I create a stand-alone binary from a Python script?
75-----------------------------------------------------------
76
77You don't need the ability to compile Python to C code if all you want is a
78stand-alone program that users can download and run without having to install
79the Python distribution first. There are a number of tools that determine the
80set of modules required by a program and bind these modules together with a
81Python binary to produce a single executable.
82
83One is to use the freeze tool, which is included in the Python source tree as
84``Tools/freeze``. It converts Python byte code to C arrays; a C compiler you can
85embed all your modules into a new program, which is then linked with the
86standard Python modules.
87
88It works by scanning your source recursively for import statements (in both
89forms) and looking for the modules in the standard Python path as well as in the
90source directory (for built-in modules). It then turns the bytecode for modules
91written in Python into C code (array initializers that can be turned into code
92objects using the marshal module) and creates a custom-made config file that
93only contains those built-in modules which are actually used in the program. It
94then compiles the generated C code and links it with the rest of the Python
95interpreter to form a self-contained binary which acts exactly like your script.
96
97Obviously, freeze requires a C compiler. There are several other utilities
98which don't. One is Thomas Heller's py2exe (Windows only) at
99
100 http://www.py2exe.org/
101
102Another is Christian Tismer's `SQFREEZE <http://starship.python.net/crew/pirx>`_
103which appends the byte code to a specially-prepared Python interpreter that can
104find the byte code in the executable.
105
106Other tools include Fredrik Lundh's `Squeeze
107<http://www.pythonware.com/products/python/squeeze>`_ and Anthony Tuininga's
108`cx_Freeze <http://starship.python.net/crew/atuining/cx_Freeze/index.html>`_.
109
110
111Are there coding standards or a style guide for Python programs?
112----------------------------------------------------------------
113
114Yes. The coding style required for standard library modules is documented as
115:pep:`8`.
116
117
118My program is too slow. How do I speed it up?
119---------------------------------------------
120
121That's a tough one, in general. There are many tricks to speed up Python code;
122consider rewriting parts in C as a last resort.
123
124In some cases it's possible to automatically translate Python to C or x86
125assembly language, meaning that you don't have to modify your code to gain
126increased speed.
127
128.. XXX seems to have overlap with other questions!
129
Antoine Pitrou09264b62011-02-05 10:57:17 +0000130`Cython <http://cython.org>`_ and `Pyrex <http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/>`_
131can compile a slightly modified version of Python code into a C extension, and
132can be used on many different platforms.
Georg Brandld7413152009-10-11 21:25:26 +0000133
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 Brandle1eef412011-08-25 11:52:26 +0200174 for i in range(3):
Georg Brandld7413152009-10-11 21:25:26 +0000175 L2.append(L1[i])
176
177it is much shorter and far faster to use ::
178
Georg Brandl62eaaf62009-12-19 17:51:41 +0000179 L2 = list(L1[:3]) # "list" is redundant if L1 is a list.
Georg Brandld7413152009-10-11 21:25:26 +0000180
Georg Brandlc4a55fc2010-02-06 18:46:57 +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 Brandld7413152009-10-11 21:25:26 +0000185
Georg Brandl11b63622009-12-20 14:21:27 +0000186 >>> list(zip([1, 2, 3], [4, 5, 6]))
Georg Brandld7413152009-10-11 21:25:26 +0000187 [(1, 4), (2, 5), (3, 6)]
188
189or to compute a number of sines::
190
Georg Brandl62eaaf62009-12-19 17:51:41 +0000191 >>> list(map(math.sin, (1, 2, 3, 4)))
192 [0.841470984808, 0.909297426826, 0.14112000806, -0.756802495308]
Georg Brandld7413152009-10-11 21:25:26 +0000193
194The operation completes very quickly in such cases.
195
Georg Brandl11b63622009-12-20 14:21:27 +0000196Other examples include the ``join()`` and ``split()`` :ref:`methods
197of string objects <string-methods>`.
198
Georg Brandld7413152009-10-11 21:25:26 +0000199For example if s1..s7 are large (10K+) strings then
200``"".join([s1,s2,s3,s4,s5,s6,s7])`` may be far faster than the more obvious
201``s1+s2+s3+s4+s5+s6+s7``, since the "summation" will compute many
202subexpressions, whereas ``join()`` does all the copying in one pass. For
Georg Brandl11b63622009-12-20 14:21:27 +0000203manipulating strings, use the ``replace()`` and the ``format()`` :ref:`methods
204on string objects <string-methods>`. Use regular expressions only when you're
205not dealing with constant string patterns.
Georg Brandld7413152009-10-11 21:25:26 +0000206
Georg Brandlc4a55fc2010-02-06 18:46:57 +0000207Be sure to use the :meth:`list.sort` built-in method to do sorting, and see the
Georg Brandld7413152009-10-11 21:25:26 +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 Brandl62eaaf62009-12-19 17:51:41 +0000215notice that ``ff()``::
Georg Brandld7413152009-10-11 21:25:26 +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 Murrayc04a6942009-11-14 22:21:32 +0000282Why am I getting an UnboundLocalError when the variable has a value?
283--------------------------------------------------------------------
Georg Brandld7413152009-10-11 21:25:26 +0000284
R. David Murrayc04a6942009-11-14 22:21:32 +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 Brandld7413152009-10-11 21:25:26 +0000288
R. David Murrayc04a6942009-11-14 22:21:32 +0000289This code:
Georg Brandld7413152009-10-11 21:25:26 +0000290
R. David Murrayc04a6942009-11-14 22:21:32 +0000291 >>> x = 10
292 >>> def bar():
293 ... print(x)
294 >>> bar()
295 10
Georg Brandld7413152009-10-11 21:25:26 +0000296
R. David Murrayc04a6942009-11-14 22:21:32 +0000297works, but this code:
Georg Brandld7413152009-10-11 21:25:26 +0000298
R. David Murrayc04a6942009-11-14 22:21:32 +0000299 >>> x = 10
300 >>> def foo():
301 ... print(x)
302 ... x += 1
Georg Brandld7413152009-10-11 21:25:26 +0000303
R. David Murrayc04a6942009-11-14 22:21:32 +0000304results in an UnboundLocalError:
Georg Brandld7413152009-10-11 21:25:26 +0000305
R. David Murrayc04a6942009-11-14 22:21:32 +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
R. David Murray18163c32009-11-14 22:27:22 +0000315earlier ``print(x)`` attempts to print the uninitialized local variable and
R. David Murrayc04a6942009-11-14 22:21:32 +0000316an 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
336You can do a similar thing in a nested scope using the :keyword:`nonlocal`
337keyword:
338
339 >>> def foo():
340 ... x = 10
341 ... def bar():
342 ... nonlocal x
343 ... print(x)
344 ... x += 1
345 ... bar()
346 ... print(x)
347 >>> foo()
348 10
349 11
Georg Brandld7413152009-10-11 21:25:26 +0000350
351
352What are the rules for local and global variables in Python?
353------------------------------------------------------------
354
355In Python, variables that are only referenced inside a function are implicitly
356global. If a variable is assigned a new value anywhere within the function's
357body, it's assumed to be a local. If a variable is ever assigned a new value
358inside the function, the variable is implicitly local, and you need to
359explicitly declare it as 'global'.
360
361Though a bit surprising at first, a moment's consideration explains this. On
362one hand, requiring :keyword:`global` for assigned variables provides a bar
363against unintended side-effects. On the other hand, if ``global`` was required
364for all global references, you'd be using ``global`` all the time. You'd have
Georg Brandlc4a55fc2010-02-06 18:46:57 +0000365to declare as global every reference to a built-in function or to a component of
Georg Brandld7413152009-10-11 21:25:26 +0000366an imported module. This clutter would defeat the usefulness of the ``global``
367declaration for identifying side-effects.
368
369
370How do I share global variables across modules?
371------------------------------------------------
372
373The canonical way to share information across modules within a single program is
374to create a special module (often called config or cfg). Just import the config
375module in all modules of your application; the module then becomes available as
376a global name. Because there is only one instance of each module, any changes
377made to the module object get reflected everywhere. For example:
378
379config.py::
380
381 x = 0 # Default value of the 'x' configuration setting
382
383mod.py::
384
385 import config
386 config.x = 1
387
388main.py::
389
390 import config
391 import mod
Georg Brandl62eaaf62009-12-19 17:51:41 +0000392 print(config.x)
Georg Brandld7413152009-10-11 21:25:26 +0000393
394Note that using a module is also the basis for implementing the Singleton design
395pattern, for the same reason.
396
397
398What are the "best practices" for using import in a module?
399-----------------------------------------------------------
400
401In general, don't use ``from modulename import *``. Doing so clutters the
402importer's namespace. Some people avoid this idiom even with the few modules
403that were designed to be imported in this manner. Modules designed in this
Georg Brandld404fa62009-10-13 16:55:12 +0000404manner include :mod:`tkinter`, and :mod:`threading`.
Georg Brandld7413152009-10-11 21:25:26 +0000405
406Import modules at the top of a file. Doing so makes it clear what other modules
407your code requires and avoids questions of whether the module name is in scope.
408Using one import per line makes it easy to add and delete module imports, but
409using multiple imports per line uses less screen space.
410
411It's good practice if you import modules in the following order:
412
Georg Brandl62eaaf62009-12-19 17:51:41 +00004131. standard library modules -- e.g. ``sys``, ``os``, ``getopt``, ``re``
Georg Brandld7413152009-10-11 21:25:26 +00004142. third-party library modules (anything installed in Python's site-packages
415 directory) -- e.g. mx.DateTime, ZODB, PIL.Image, etc.
4163. locally-developed modules
417
418Never use relative package imports. If you're writing code that's in the
419``package.sub.m1`` module and want to import ``package.sub.m2``, do not just
Georg Brandl11b63622009-12-20 14:21:27 +0000420write ``from . import m2``, even though it's legal. Write ``from package.sub
421import m2`` instead. See :pep:`328` for details.
Georg Brandld7413152009-10-11 21:25:26 +0000422
423It is sometimes necessary to move imports to a function or class to avoid
424problems with circular imports. Gordon McMillan says:
425
426 Circular imports are fine where both modules use the "import <module>" form
427 of import. They fail when the 2nd module wants to grab a name out of the
428 first ("from module import name") and the import is at the top level. That's
429 because names in the 1st are not yet available, because the first module is
430 busy importing the 2nd.
431
432In this case, if the second module is only used in one function, then the import
433can easily be moved into that function. By the time the import is called, the
434first module will have finished initializing, and the second module can do its
435import.
436
437It may also be necessary to move imports out of the top level of code if some of
438the modules are platform-specific. In that case, it may not even be possible to
439import all of the modules at the top of the file. In this case, importing the
440correct modules in the corresponding platform-specific code is a good option.
441
442Only move imports into a local scope, such as inside a function definition, if
443it's necessary to solve a problem such as avoiding a circular import or are
444trying to reduce the initialization time of a module. This technique is
445especially helpful if many of the imports are unnecessary depending on how the
446program executes. You may also want to move imports into a function if the
447modules are only ever used in that function. Note that loading a module the
448first time may be expensive because of the one time initialization of the
449module, but loading a module multiple times is virtually free, costing only a
450couple of dictionary lookups. Even if the module name has gone out of scope,
451the module is probably available in :data:`sys.modules`.
452
453If only instances of a specific class use a module, then it is reasonable to
454import the module in the class's ``__init__`` method and then assign the module
455to an instance variable so that the module is always available (via that
456instance variable) during the life of the object. Note that to delay an import
457until the class is instantiated, the import must be inside a method. Putting
458the import inside the class but outside of any method still causes the import to
459occur when the module is initialized.
460
461
462How can I pass optional or keyword parameters from one function to another?
463---------------------------------------------------------------------------
464
465Collect the arguments using the ``*`` and ``**`` specifiers in the function's
466parameter list; this gives you the positional arguments as a tuple and the
467keyword arguments as a dictionary. You can then pass these arguments when
468calling another function by using ``*`` and ``**``::
469
470 def f(x, *args, **kwargs):
471 ...
472 kwargs['width'] = '14.3c'
473 ...
474 g(x, *args, **kwargs)
475
Georg Brandld7413152009-10-11 21:25:26 +0000476
477How do I write a function with output parameters (call by reference)?
478---------------------------------------------------------------------
479
480Remember that arguments are passed by assignment in Python. Since assignment
481just creates references to objects, there's no alias between an argument name in
482the caller and callee, and so no call-by-reference per se. You can achieve the
483desired effect in a number of ways.
484
4851) By returning a tuple of the results::
486
487 def func2(a, b):
488 a = 'new-value' # a and b are local names
489 b = b + 1 # assigned to new objects
490 return a, b # return new values
491
492 x, y = 'old-value', 99
493 x, y = func2(x, y)
Georg Brandl62eaaf62009-12-19 17:51:41 +0000494 print(x, y) # output: new-value 100
Georg Brandld7413152009-10-11 21:25:26 +0000495
496 This is almost always the clearest solution.
497
4982) By using global variables. This isn't thread-safe, and is not recommended.
499
5003) By passing a mutable (changeable in-place) object::
501
502 def func1(a):
503 a[0] = 'new-value' # 'a' references a mutable list
504 a[1] = a[1] + 1 # changes a shared object
505
506 args = ['old-value', 99]
507 func1(args)
Georg Brandl62eaaf62009-12-19 17:51:41 +0000508 print(args[0], args[1]) # output: new-value 100
Georg Brandld7413152009-10-11 21:25:26 +0000509
5104) By passing in a dictionary that gets mutated::
511
512 def func3(args):
513 args['a'] = 'new-value' # args is a mutable dictionary
514 args['b'] = args['b'] + 1 # change it in-place
515
516 args = {'a':' old-value', 'b': 99}
517 func3(args)
Georg Brandl62eaaf62009-12-19 17:51:41 +0000518 print(args['a'], args['b'])
Georg Brandld7413152009-10-11 21:25:26 +0000519
5205) Or bundle up values in a class instance::
521
522 class callByRef:
523 def __init__(self, **args):
524 for (key, value) in args.items():
525 setattr(self, key, value)
526
527 def func4(args):
528 args.a = 'new-value' # args is a mutable callByRef
529 args.b = args.b + 1 # change object in-place
530
531 args = callByRef(a='old-value', b=99)
532 func4(args)
Georg Brandl62eaaf62009-12-19 17:51:41 +0000533 print(args.a, args.b)
Georg Brandld7413152009-10-11 21:25:26 +0000534
535
536 There's almost never a good reason to get this complicated.
537
538Your best choice is to return a tuple containing the multiple results.
539
540
541How do you make a higher order function in Python?
542--------------------------------------------------
543
544You have two choices: you can use nested scopes or you can use callable objects.
545For example, suppose you wanted to define ``linear(a,b)`` which returns a
546function ``f(x)`` that computes the value ``a*x+b``. Using nested scopes::
547
548 def linear(a, b):
549 def result(x):
550 return a * x + b
551 return result
552
553Or using a callable object::
554
555 class linear:
556
557 def __init__(self, a, b):
558 self.a, self.b = a, b
559
560 def __call__(self, x):
561 return self.a * x + self.b
562
563In both cases, ::
564
565 taxes = linear(0.3, 2)
566
567gives a callable object where ``taxes(10e6) == 0.3 * 10e6 + 2``.
568
569The callable object approach has the disadvantage that it is a bit slower and
570results in slightly longer code. However, note that a collection of callables
571can share their signature via inheritance::
572
573 class exponential(linear):
574 # __init__ inherited
575 def __call__(self, x):
576 return self.a * (x ** self.b)
577
578Object can encapsulate state for several methods::
579
580 class counter:
581
582 value = 0
583
584 def set(self, x):
585 self.value = x
586
587 def up(self):
588 self.value = self.value + 1
589
590 def down(self):
591 self.value = self.value - 1
592
593 count = counter()
594 inc, dec, reset = count.up, count.down, count.set
595
596Here ``inc()``, ``dec()`` and ``reset()`` act like functions which share the
597same counting variable.
598
599
600How do I copy an object in Python?
601----------------------------------
602
603In general, try :func:`copy.copy` or :func:`copy.deepcopy` for the general case.
604Not all objects can be copied, but most can.
605
606Some objects can be copied more easily. Dictionaries have a :meth:`~dict.copy`
607method::
608
609 newdict = olddict.copy()
610
611Sequences can be copied by slicing::
612
613 new_l = l[:]
614
615
616How can I find the methods or attributes of an object?
617------------------------------------------------------
618
619For an instance x of a user-defined class, ``dir(x)`` returns an alphabetized
620list of the names containing the instance attributes and methods and attributes
621defined by its class.
622
623
624How can my code discover the name of an object?
625-----------------------------------------------
626
627Generally speaking, it can't, because objects don't really have names.
628Essentially, assignment always binds a name to a value; The same is true of
629``def`` and ``class`` statements, but in that case the value is a
630callable. Consider the following code::
631
632 class A:
633 pass
634
635 B = A
636
637 a = B()
638 b = a
Georg Brandl62eaaf62009-12-19 17:51:41 +0000639 print(b)
640 <__main__.A object at 0x16D07CC>
641 print(a)
642 <__main__.A object at 0x16D07CC>
Georg Brandld7413152009-10-11 21:25:26 +0000643
644Arguably the class has a name: even though it is bound to two names and invoked
645through the name B the created instance is still reported as an instance of
646class A. However, it is impossible to say whether the instance's name is a or
647b, since both names are bound to the same value.
648
649Generally speaking it should not be necessary for your code to "know the names"
650of particular values. Unless you are deliberately writing introspective
651programs, this is usually an indication that a change of approach might be
652beneficial.
653
654In comp.lang.python, Fredrik Lundh once gave an excellent analogy in answer to
655this question:
656
657 The same way as you get the name of that cat you found on your porch: the cat
658 (object) itself cannot tell you its name, and it doesn't really care -- so
659 the only way to find out what it's called is to ask all your neighbours
660 (namespaces) if it's their cat (object)...
661
662 ....and don't be surprised if you'll find that it's known by many names, or
663 no name at all!
664
665
666What's up with the comma operator's precedence?
667-----------------------------------------------
668
669Comma is not an operator in Python. Consider this session::
670
671 >>> "a" in "b", "a"
Georg Brandl62eaaf62009-12-19 17:51:41 +0000672 (False, 'a')
Georg Brandld7413152009-10-11 21:25:26 +0000673
674Since the comma is not an operator, but a separator between expressions the
675above is evaluated as if you had entered::
676
677 >>> ("a" in "b"), "a"
678
679not::
680
Georg Brandl62eaaf62009-12-19 17:51:41 +0000681 >>> "a" in ("b", "a")
Georg Brandld7413152009-10-11 21:25:26 +0000682
683The same is true of the various assignment operators (``=``, ``+=`` etc). They
684are not truly operators but syntactic delimiters in assignment statements.
685
686
687Is there an equivalent of C's "?:" ternary operator?
688----------------------------------------------------
689
690Yes, this feature was added in Python 2.5. The syntax would be as follows::
691
692 [on_true] if [expression] else [on_false]
693
694 x, y = 50, 25
695
696 small = x if x < y else y
697
698For versions previous to 2.5 the answer would be 'No'.
699
700.. XXX remove rest?
701
702In many cases you can mimic ``a ? b : c`` with ``a and b or c``, but there's a
703flaw: if *b* is zero (or empty, or ``None`` -- anything that tests false) then
704*c* will be selected instead. In many cases you can prove by looking at the
705code that this can't happen (e.g. because *b* is a constant or has a type that
706can never be false), but in general this can be a problem.
707
708Tim Peters (who wishes it was Steve Majewski) suggested the following solution:
709``(a and [b] or [c])[0]``. Because ``[b]`` is a singleton list it is never
710false, so the wrong path is never taken; then applying ``[0]`` to the whole
711thing gets the *b* or *c* that you really wanted. Ugly, but it gets you there
712in the rare cases where it is really inconvenient to rewrite your code using
713'if'.
714
715The best course is usually to write a simple ``if...else`` statement. Another
716solution is to implement the ``?:`` operator as a function::
717
718 def q(cond, on_true, on_false):
719 if cond:
720 if not isfunction(on_true):
721 return on_true
722 else:
Georg Brandl62eaaf62009-12-19 17:51:41 +0000723 return on_true()
Georg Brandld7413152009-10-11 21:25:26 +0000724 else:
725 if not isfunction(on_false):
726 return on_false
727 else:
Georg Brandl62eaaf62009-12-19 17:51:41 +0000728 return on_false()
Georg Brandld7413152009-10-11 21:25:26 +0000729
730In most cases you'll pass b and c directly: ``q(a, b, c)``. To avoid evaluating
731b or c when they shouldn't be, encapsulate them within a lambda function, e.g.:
732``q(a, lambda: b, lambda: c)``.
733
734It has been asked *why* Python has no if-then-else expression. There are
735several answers: many languages do just fine without one; it can easily lead to
736less readable code; no sufficiently "Pythonic" syntax has been discovered; a
737search of the standard library found remarkably few places where using an
738if-then-else expression would make the code more understandable.
739
740In 2002, :pep:`308` was written proposing several possible syntaxes and the
741community was asked to vote on the issue. The vote was inconclusive. Most
742people liked one of the syntaxes, but also hated other syntaxes; many votes
743implied that people preferred no ternary operator rather than having a syntax
744they hated.
745
746
747Is it possible to write obfuscated one-liners in Python?
748--------------------------------------------------------
749
750Yes. Usually this is done by nesting :keyword:`lambda` within
751:keyword:`lambda`. See the following three examples, due to Ulf Bartelt::
752
Georg Brandl62eaaf62009-12-19 17:51:41 +0000753 from functools import reduce
754
Georg Brandld7413152009-10-11 21:25:26 +0000755 # Primes < 1000
Georg Brandl62eaaf62009-12-19 17:51:41 +0000756 print(list(filter(None,map(lambda y:y*reduce(lambda x,y:x*y!=0,
757 map(lambda x,y=y:y%x,range(2,int(pow(y,0.5)+1))),1),range(2,1000)))))
Georg Brandld7413152009-10-11 21:25:26 +0000758
759 # First 10 Fibonacci numbers
Georg Brandl62eaaf62009-12-19 17:51:41 +0000760 print(list(map(lambda x,f=lambda x,f:(f(x-1,f)+f(x-2,f)) if x>1 else 1:
761 f(x,f), range(10))))
Georg Brandld7413152009-10-11 21:25:26 +0000762
763 # Mandelbrot set
Georg Brandl62eaaf62009-12-19 17:51:41 +0000764 print((lambda Ru,Ro,Iu,Io,IM,Sx,Sy:reduce(lambda x,y:x+y,map(lambda y,
Georg Brandld7413152009-10-11 21:25:26 +0000765 Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,Sy=Sy,L=lambda yc,Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,i=IM,
766 Sx=Sx,Sy=Sy:reduce(lambda x,y:x+y,map(lambda x,xc=Ru,yc=yc,Ru=Ru,Ro=Ro,
767 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
768 >=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(
769 64+F(Ru+x*(Ro-Ru)/Sx,yc,0,0,i)),range(Sx))):L(Iu+y*(Io-Iu)/Sy),range(Sy
Georg Brandl62eaaf62009-12-19 17:51:41 +0000770 ))))(-2.1, 0.7, -1.2, 1.2, 30, 80, 24))
Georg Brandld7413152009-10-11 21:25:26 +0000771 # \___ ___/ \___ ___/ | | |__ lines on screen
772 # V V | |______ columns on screen
773 # | | |__________ maximum of "iterations"
774 # | |_________________ range on y axis
775 # |____________________________ range on x axis
776
777Don't try this at home, kids!
778
779
780Numbers and strings
781===================
782
783How do I specify hexadecimal and octal integers?
784------------------------------------------------
785
Georg Brandl62eaaf62009-12-19 17:51:41 +0000786To specify an octal digit, precede the octal value with a zero, and then a lower
787or uppercase "o". For example, to set the variable "a" to the octal value "10"
788(8 in decimal), type::
Georg Brandld7413152009-10-11 21:25:26 +0000789
Georg Brandl62eaaf62009-12-19 17:51:41 +0000790 >>> a = 0o10
Georg Brandld7413152009-10-11 21:25:26 +0000791 >>> a
792 8
793
794Hexadecimal is just as easy. Simply precede the hexadecimal number with a zero,
795and then a lower or uppercase "x". Hexadecimal digits can be specified in lower
796or uppercase. For example, in the Python interpreter::
797
798 >>> a = 0xa5
799 >>> a
800 165
801 >>> b = 0XB2
802 >>> b
803 178
804
805
Georg Brandl62eaaf62009-12-19 17:51:41 +0000806Why does -22 // 10 return -3?
807-----------------------------
Georg Brandld7413152009-10-11 21:25:26 +0000808
809It's primarily driven by the desire that ``i % j`` have the same sign as ``j``.
810If you want that, and also want::
811
Georg Brandl62eaaf62009-12-19 17:51:41 +0000812 i == (i // j) * j + (i % j)
Georg Brandld7413152009-10-11 21:25:26 +0000813
814then integer division has to return the floor. C also requires that identity to
Georg Brandl62eaaf62009-12-19 17:51:41 +0000815hold, and then compilers that truncate ``i // j`` need to make ``i % j`` have
816the same sign as ``i``.
Georg Brandld7413152009-10-11 21:25:26 +0000817
818There are few real use cases for ``i % j`` when ``j`` is negative. When ``j``
819is positive, there are many, and in virtually all of them it's more useful for
820``i % j`` to be ``>= 0``. If the clock says 10 now, what did it say 200 hours
821ago? ``-190 % 12 == 2`` is useful; ``-190 % 12 == -10`` is a bug waiting to
822bite.
823
824
825How do I convert a string to a number?
826--------------------------------------
827
828For integers, use the built-in :func:`int` type constructor, e.g. ``int('144')
829== 144``. Similarly, :func:`float` converts to floating-point,
830e.g. ``float('144') == 144.0``.
831
832By default, these interpret the number as decimal, so that ``int('0144') ==
833144`` and ``int('0x144')`` raises :exc:`ValueError`. ``int(string, base)`` takes
834the base to convert from as a second optional argument, so ``int('0x144', 16) ==
835324``. If the base is specified as 0, the number is interpreted using Python's
836rules: a leading '0' indicates octal, and '0x' indicates a hex number.
837
838Do not use the built-in function :func:`eval` if all you need is to convert
839strings to numbers. :func:`eval` will be significantly slower and it presents a
840security risk: someone could pass you a Python expression that might have
841unwanted side effects. For example, someone could pass
842``__import__('os').system("rm -rf $HOME")`` which would erase your home
843directory.
844
845:func:`eval` also has the effect of interpreting numbers as Python expressions,
Georg Brandl62eaaf62009-12-19 17:51:41 +0000846so that e.g. ``eval('09')`` gives a syntax error because Python does not allow
847leading '0' in a decimal number (except '0').
Georg Brandld7413152009-10-11 21:25:26 +0000848
849
850How do I convert a number to a string?
851--------------------------------------
852
853To convert, e.g., the number 144 to the string '144', use the built-in type
854constructor :func:`str`. If you want a hexadecimal or octal representation, use
Georg Brandl62eaaf62009-12-19 17:51:41 +0000855the built-in functions :func:`hex` or :func:`oct`. For fancy formatting, see
856the :ref:`string-formatting` section, e.g. ``"{:04d}".format(144)`` yields
Georg Brandl11b63622009-12-20 14:21:27 +0000857``'0144'`` and ``"{:.3f}".format(1/3)`` yields ``'0.333'``.
Georg Brandld7413152009-10-11 21:25:26 +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)
Georg Brandl62eaaf62009-12-19 17:51:41 +0000868 >>> print(a)
Georg Brandld7413152009-10-11 21:25:26 +0000869 ['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
Georg Brandl62eaaf62009-12-19 17:51:41 +0000875 >>> a = array.array('u', s)
876 >>> print(a)
877 array('u', 'Hello, world')
878 >>> a[0] = 'y'
879 >>> print(a)
880 array('u', 'yello world')
881 >>> a.tounicode()
Georg Brandld7413152009-10-11 21:25:26 +0000882 'yello, world'
883
884
885How do I use strings to call functions/methods?
886-----------------------------------------------
887
888There are various techniques.
889
890* The best is to use a dictionary that maps strings to functions. The primary
891 advantage of this technique is that the strings do not need to match the names
892 of the functions. This is also the primary technique used to emulate a case
893 construct::
894
895 def a():
896 pass
897
898 def b():
899 pass
900
901 dispatch = {'go': a, 'stop': b} # Note lack of parens for funcs
902
903 dispatch[get_input()]() # Note trailing parens to call function
904
905* Use the built-in function :func:`getattr`::
906
907 import foo
908 getattr(foo, 'bar')()
909
910 Note that :func:`getattr` works on any object, including classes, class
911 instances, modules, and so on.
912
913 This is used in several places in the standard library, like this::
914
915 class Foo:
916 def do_foo(self):
917 ...
918
919 def do_bar(self):
920 ...
921
922 f = getattr(foo_instance, 'do_' + opname)
923 f()
924
925
926* Use :func:`locals` or :func:`eval` to resolve the function name::
927
928 def myFunc():
Georg Brandl62eaaf62009-12-19 17:51:41 +0000929 print("hello")
Georg Brandld7413152009-10-11 21:25:26 +0000930
931 fname = "myFunc"
932
933 f = locals()[fname]
934 f()
935
936 f = eval(fname)
937 f()
938
939 Note: Using :func:`eval` is slow and dangerous. If you don't have absolute
940 control over the contents of the string, someone could pass a string that
941 resulted in an arbitrary function being executed.
942
943Is there an equivalent to Perl's chomp() for removing trailing newlines from strings?
944-------------------------------------------------------------------------------------
945
946Starting with Python 2.2, you can use ``S.rstrip("\r\n")`` to remove all
Georg Brandl6faee4e2010-09-21 14:48:28 +0000947occurrences of any line terminator from the end of the string ``S`` without
Georg Brandld7413152009-10-11 21:25:26 +0000948removing other trailing whitespace. If the string ``S`` represents more than
949one line, with several empty lines at the end, the line terminators for all the
950blank lines will be removed::
951
952 >>> lines = ("line 1 \r\n"
953 ... "\r\n"
954 ... "\r\n")
955 >>> lines.rstrip("\n\r")
Georg Brandl62eaaf62009-12-19 17:51:41 +0000956 'line 1 '
Georg Brandld7413152009-10-11 21:25:26 +0000957
958Since this is typically only desired when reading text one line at a time, using
959``S.rstrip()`` this way works well.
960
Georg Brandl62eaaf62009-12-19 17:51:41 +0000961For older versions of Python, there are two partial substitutes:
Georg Brandld7413152009-10-11 21:25:26 +0000962
963- If you want to remove all trailing whitespace, use the ``rstrip()`` method of
964 string objects. This removes all trailing whitespace, not just a single
965 newline.
966
967- Otherwise, if there is only one line in the string ``S``, use
968 ``S.splitlines()[0]``.
969
970
971Is there a scanf() or sscanf() equivalent?
972------------------------------------------
973
974Not as such.
975
976For simple input parsing, the easiest approach is usually to split the line into
977whitespace-delimited words using the :meth:`~str.split` method of string objects
978and then convert decimal strings to numeric values using :func:`int` or
979:func:`float`. ``split()`` supports an optional "sep" parameter which is useful
980if the line uses something other than whitespace as a separator.
981
Brian Curtin5a7a52f2010-09-23 13:45:21 +0000982For more complicated input parsing, regular expressions are more powerful
Georg Brandl60203b42010-10-06 10:11:56 +0000983than C's :c:func:`sscanf` and better suited for the task.
Georg Brandld7413152009-10-11 21:25:26 +0000984
985
Georg Brandl62eaaf62009-12-19 17:51:41 +0000986What does 'UnicodeDecodeError' or 'UnicodeEncodeError' error mean?
987-------------------------------------------------------------------
Georg Brandld7413152009-10-11 21:25:26 +0000988
Georg Brandl62eaaf62009-12-19 17:51:41 +0000989See the :ref:`unicode-howto`.
Georg Brandld7413152009-10-11 21:25:26 +0000990
991
Antoine Pitroufd9ebd42011-11-25 16:33:53 +0100992What is the most efficient way to concatenate many strings together?
993--------------------------------------------------------------------
994
995:class:`str` and :class:`bytes` objects are immutable, therefore concatenating
996many strings together is inefficient as each concatenation creates a new
997object. In the general case, the total runtime cost is quadratic in the
998total string length.
999
1000To accumulate many :class:`str` objects, the recommended idiom is to place
1001them into a list and call :meth:`str.join` at the end::
1002
1003 chunks = []
1004 for s in my_strings:
1005 chunks.append(s)
1006 result = ''.join(chunks)
1007
1008(another reasonably efficient idiom is to use :class:`io.StringIO`)
1009
1010To accumulate many :class:`bytes` objects, the recommended idiom is to extend
1011a :class:`bytearray` object using in-place concatenation (the ``+=`` operator)::
1012
1013 result = bytearray()
1014 for b in my_bytes_objects:
1015 result += b
1016
1017
Georg Brandld7413152009-10-11 21:25:26 +00001018Sequences (Tuples/Lists)
1019========================
1020
1021How do I convert between tuples and lists?
1022------------------------------------------
1023
1024The type constructor ``tuple(seq)`` converts any sequence (actually, any
1025iterable) into a tuple with the same items in the same order.
1026
1027For example, ``tuple([1, 2, 3])`` yields ``(1, 2, 3)`` and ``tuple('abc')``
1028yields ``('a', 'b', 'c')``. If the argument is a tuple, it does not make a copy
1029but returns the same object, so it is cheap to call :func:`tuple` when you
1030aren't sure that an object is already a tuple.
1031
1032The type constructor ``list(seq)`` converts any sequence or iterable into a list
1033with the same items in the same order. For example, ``list((1, 2, 3))`` yields
1034``[1, 2, 3]`` and ``list('abc')`` yields ``['a', 'b', 'c']``. If the argument
1035is a list, it makes a copy just like ``seq[:]`` would.
1036
1037
1038What's a negative index?
1039------------------------
1040
1041Python sequences are indexed with positive numbers and negative numbers. For
1042positive numbers 0 is the first index 1 is the second index and so forth. For
1043negative indices -1 is the last index and -2 is the penultimate (next to last)
1044index and so forth. Think of ``seq[-n]`` as the same as ``seq[len(seq)-n]``.
1045
1046Using negative indices can be very convenient. For example ``S[:-1]`` is all of
1047the string except for its last character, which is useful for removing the
1048trailing newline from a string.
1049
1050
1051How do I iterate over a sequence in reverse order?
1052--------------------------------------------------
1053
Georg Brandlc4a55fc2010-02-06 18:46:57 +00001054Use the :func:`reversed` built-in function, which is new in Python 2.4::
Georg Brandld7413152009-10-11 21:25:26 +00001055
1056 for x in reversed(sequence):
1057 ... # do something with x...
1058
1059This won't touch your original sequence, but build a new copy with reversed
1060order to iterate over.
1061
1062With Python 2.3, you can use an extended slice syntax::
1063
1064 for x in sequence[::-1]:
1065 ... # do something with x...
1066
1067
1068How do you remove duplicates from a list?
1069-----------------------------------------
1070
1071See the Python Cookbook for a long discussion of many ways to do this:
1072
1073 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52560
1074
1075If you don't mind reordering the list, sort it and then scan from the end of the
1076list, deleting duplicates as you go::
1077
Georg Brandl62eaaf62009-12-19 17:51:41 +00001078 if mylist:
1079 mylist.sort()
1080 last = mylist[-1]
1081 for i in range(len(mylist)-2, -1, -1):
1082 if last == mylist[i]:
1083 del mylist[i]
Georg Brandld7413152009-10-11 21:25:26 +00001084 else:
Georg Brandl62eaaf62009-12-19 17:51:41 +00001085 last = mylist[i]
Georg Brandld7413152009-10-11 21:25:26 +00001086
1087If all elements of the list may be used as dictionary keys (i.e. they are all
1088hashable) this is often faster ::
1089
1090 d = {}
Georg Brandl62eaaf62009-12-19 17:51:41 +00001091 for x in mylist:
1092 d[x] = 1
1093 mylist = list(d.keys())
Georg Brandld7413152009-10-11 21:25:26 +00001094
1095In Python 2.5 and later, the following is possible instead::
1096
Georg Brandl62eaaf62009-12-19 17:51:41 +00001097 mylist = list(set(mylist))
Georg Brandld7413152009-10-11 21:25:26 +00001098
1099This converts the list into a set, thereby removing duplicates, and then back
1100into a list.
1101
1102
1103How do you make an array in Python?
1104-----------------------------------
1105
1106Use a list::
1107
1108 ["this", 1, "is", "an", "array"]
1109
1110Lists are equivalent to C or Pascal arrays in their time complexity; the primary
1111difference is that a Python list can contain objects of many different types.
1112
1113The ``array`` module also provides methods for creating arrays of fixed types
1114with compact representations, but they are slower to index than lists. Also
1115note that the Numeric extensions and others define array-like structures with
1116various characteristics as well.
1117
1118To get Lisp-style linked lists, you can emulate cons cells using tuples::
1119
1120 lisp_list = ("like", ("this", ("example", None) ) )
1121
1122If mutability is desired, you could use lists instead of tuples. Here the
1123analogue of lisp car is ``lisp_list[0]`` and the analogue of cdr is
1124``lisp_list[1]``. Only do this if you're sure you really need to, because it's
1125usually a lot slower than using Python lists.
1126
1127
1128How do I create a multidimensional list?
1129----------------------------------------
1130
1131You probably tried to make a multidimensional array like this::
1132
1133 A = [[None] * 2] * 3
1134
1135This looks correct if you print it::
1136
1137 >>> A
1138 [[None, None], [None, None], [None, None]]
1139
1140But when you assign a value, it shows up in multiple places:
1141
1142 >>> A[0][0] = 5
1143 >>> A
1144 [[5, None], [5, None], [5, None]]
1145
1146The reason is that replicating a list with ``*`` doesn't create copies, it only
1147creates references to the existing objects. The ``*3`` creates a list
1148containing 3 references to the same list of length two. Changes to one row will
1149show in all rows, which is almost certainly not what you want.
1150
1151The suggested approach is to create a list of the desired length first and then
1152fill in each element with a newly created list::
1153
1154 A = [None] * 3
1155 for i in range(3):
1156 A[i] = [None] * 2
1157
1158This generates a list containing 3 different lists of length two. You can also
1159use a list comprehension::
1160
1161 w, h = 2, 3
1162 A = [[None] * w for i in range(h)]
1163
1164Or, you can use an extension that provides a matrix datatype; `Numeric Python
Georg Brandl495f7b52009-10-27 15:28:25 +00001165<http://numpy.scipy.org/>`_ is the best known.
Georg Brandld7413152009-10-11 21:25:26 +00001166
1167
1168How do I apply a method to a sequence of objects?
1169-------------------------------------------------
1170
1171Use a list comprehension::
1172
Georg Brandl62eaaf62009-12-19 17:51:41 +00001173 result = [obj.method() for obj in mylist]
Georg Brandld7413152009-10-11 21:25:26 +00001174
1175
1176Dictionaries
1177============
1178
1179How can I get a dictionary to display its keys in a consistent order?
1180---------------------------------------------------------------------
1181
1182You can't. Dictionaries store their keys in an unpredictable order, so the
1183display order of a dictionary's elements will be similarly unpredictable.
1184
1185This can be frustrating if you want to save a printable version to a file, make
1186some changes and then compare it with some other printed dictionary. In this
1187case, use the ``pprint`` module to pretty-print the dictionary; the items will
1188be presented in order sorted by the key.
1189
Georg Brandl62eaaf62009-12-19 17:51:41 +00001190A more complicated solution is to subclass ``dict`` to create a
Georg Brandld7413152009-10-11 21:25:26 +00001191``SortedDict`` class that prints itself in a predictable order. Here's one
1192simpleminded implementation of such a class::
1193
Georg Brandl62eaaf62009-12-19 17:51:41 +00001194 class SortedDict(dict):
Georg Brandld7413152009-10-11 21:25:26 +00001195 def __repr__(self):
Georg Brandl62eaaf62009-12-19 17:51:41 +00001196 keys = sorted(self.keys())
1197 result = ("{!r}: {!r}".format(k, self[k]) for k in keys)
1198 return "{{{}}}".format(", ".join(result))
Georg Brandld7413152009-10-11 21:25:26 +00001199
Georg Brandl62eaaf62009-12-19 17:51:41 +00001200 __str__ = __repr__
Georg Brandld7413152009-10-11 21:25:26 +00001201
1202This will work for many common situations you might encounter, though it's far
1203from a perfect solution. The largest flaw is that if some values in the
1204dictionary are also dictionaries, their values won't be presented in any
1205particular order.
1206
1207
1208I want to do a complicated sort: can you do a Schwartzian Transform in Python?
1209------------------------------------------------------------------------------
1210
1211The technique, attributed to Randal Schwartz of the Perl community, sorts the
1212elements of a list by a metric which maps each element to its "sort value". In
1213Python, just use the ``key`` argument for the ``sort()`` method::
1214
1215 Isorted = L[:]
1216 Isorted.sort(key=lambda s: int(s[10:15]))
1217
1218The ``key`` argument is new in Python 2.4, for older versions this kind of
1219sorting is quite simple to do with list comprehensions. To sort a list of
1220strings by their uppercase values::
1221
Georg Brandl62eaaf62009-12-19 17:51:41 +00001222 tmp1 = [(x.upper(), x) for x in L] # Schwartzian transform
Georg Brandld7413152009-10-11 21:25:26 +00001223 tmp1.sort()
1224 Usorted = [x[1] for x in tmp1]
1225
1226To sort by the integer value of a subfield extending from positions 10-15 in
1227each string::
1228
Georg Brandl62eaaf62009-12-19 17:51:41 +00001229 tmp2 = [(int(s[10:15]), s) for s in L] # Schwartzian transform
Georg Brandld7413152009-10-11 21:25:26 +00001230 tmp2.sort()
1231 Isorted = [x[1] for x in tmp2]
1232
Georg Brandl62eaaf62009-12-19 17:51:41 +00001233For versions prior to 3.0, Isorted may also be computed by ::
Georg Brandld7413152009-10-11 21:25:26 +00001234
1235 def intfield(s):
1236 return int(s[10:15])
1237
1238 def Icmp(s1, s2):
1239 return cmp(intfield(s1), intfield(s2))
1240
1241 Isorted = L[:]
1242 Isorted.sort(Icmp)
1243
1244but since this method calls ``intfield()`` many times for each element of L, it
1245is slower than the Schwartzian Transform.
1246
1247
1248How can I sort one list by values from another list?
1249----------------------------------------------------
1250
Georg Brandl62eaaf62009-12-19 17:51:41 +00001251Merge them into an iterator of tuples, sort the resulting list, and then pick
Georg Brandld7413152009-10-11 21:25:26 +00001252out the element you want. ::
1253
1254 >>> list1 = ["what", "I'm", "sorting", "by"]
1255 >>> list2 = ["something", "else", "to", "sort"]
1256 >>> pairs = zip(list1, list2)
Georg Brandl62eaaf62009-12-19 17:51:41 +00001257 >>> pairs = sorted(pairs)
Georg Brandld7413152009-10-11 21:25:26 +00001258 >>> pairs
Georg Brandl62eaaf62009-12-19 17:51:41 +00001259 [("I'm", 'else'), ('by', 'sort'), ('sorting', 'to'), ('what', 'something')]
1260 >>> result = [x[1] for x in pairs]
Georg Brandld7413152009-10-11 21:25:26 +00001261 >>> result
1262 ['else', 'sort', 'to', 'something']
1263
Georg Brandl62eaaf62009-12-19 17:51:41 +00001264
Georg Brandld7413152009-10-11 21:25:26 +00001265An alternative for the last step is::
1266
Georg Brandl62eaaf62009-12-19 17:51:41 +00001267 >>> result = []
1268 >>> for p in pairs: result.append(p[1])
Georg Brandld7413152009-10-11 21:25:26 +00001269
1270If you find this more legible, you might prefer to use this instead of the final
1271list comprehension. However, it is almost twice as slow for long lists. Why?
1272First, the ``append()`` operation has to reallocate memory, and while it uses
1273some tricks to avoid doing that each time, it still has to do it occasionally,
1274and that costs quite a bit. Second, the expression "result.append" requires an
1275extra attribute lookup, and third, there's a speed reduction from having to make
1276all those function calls.
1277
1278
1279Objects
1280=======
1281
1282What is a class?
1283----------------
1284
1285A class is the particular object type created by executing a class statement.
1286Class objects are used as templates to create instance objects, which embody
1287both the data (attributes) and code (methods) specific to a datatype.
1288
1289A class can be based on one or more other classes, called its base class(es). It
1290then inherits the attributes and methods of its base classes. This allows an
1291object model to be successively refined by inheritance. You might have a
1292generic ``Mailbox`` class that provides basic accessor methods for a mailbox,
1293and subclasses such as ``MboxMailbox``, ``MaildirMailbox``, ``OutlookMailbox``
1294that handle various specific mailbox formats.
1295
1296
1297What is a method?
1298-----------------
1299
1300A method is a function on some object ``x`` that you normally call as
1301``x.name(arguments...)``. Methods are defined as functions inside the class
1302definition::
1303
1304 class C:
1305 def meth (self, arg):
1306 return arg * 2 + self.attribute
1307
1308
1309What is self?
1310-------------
1311
1312Self is merely a conventional name for the first argument of a method. A method
1313defined as ``meth(self, a, b, c)`` should be called as ``x.meth(a, b, c)`` for
1314some instance ``x`` of the class in which the definition occurs; the called
1315method will think it is called as ``meth(x, a, b, c)``.
1316
1317See also :ref:`why-self`.
1318
1319
1320How do I check if an object is an instance of a given class or of a subclass of it?
1321-----------------------------------------------------------------------------------
1322
1323Use the built-in function ``isinstance(obj, cls)``. You can check if an object
1324is an instance of any of a number of classes by providing a tuple instead of a
1325single class, e.g. ``isinstance(obj, (class1, class2, ...))``, and can also
1326check whether an object is one of Python's built-in types, e.g.
Georg Brandl62eaaf62009-12-19 17:51:41 +00001327``isinstance(obj, str)`` or ``isinstance(obj, (int, float, complex))``.
Georg Brandld7413152009-10-11 21:25:26 +00001328
1329Note that most programs do not use :func:`isinstance` on user-defined classes
1330very often. If you are developing the classes yourself, a more proper
1331object-oriented style is to define methods on the classes that encapsulate a
1332particular behaviour, instead of checking the object's class and doing a
1333different thing based on what class it is. For example, if you have a function
1334that does something::
1335
Georg Brandl62eaaf62009-12-19 17:51:41 +00001336 def search(obj):
Georg Brandld7413152009-10-11 21:25:26 +00001337 if isinstance(obj, Mailbox):
1338 # ... code to search a mailbox
1339 elif isinstance(obj, Document):
1340 # ... code to search a document
1341 elif ...
1342
1343A better approach is to define a ``search()`` method on all the classes and just
1344call it::
1345
1346 class Mailbox:
1347 def search(self):
1348 # ... code to search a mailbox
1349
1350 class Document:
1351 def search(self):
1352 # ... code to search a document
1353
1354 obj.search()
1355
1356
1357What is delegation?
1358-------------------
1359
1360Delegation is an object oriented technique (also called a design pattern).
1361Let's say you have an object ``x`` and want to change the behaviour of just one
1362of its methods. You can create a new class that provides a new implementation
1363of the method you're interested in changing and delegates all other methods to
1364the corresponding method of ``x``.
1365
1366Python programmers can easily implement delegation. For example, the following
1367class implements a class that behaves like a file but converts all written data
1368to uppercase::
1369
1370 class UpperOut:
1371
1372 def __init__(self, outfile):
1373 self._outfile = outfile
1374
1375 def write(self, s):
1376 self._outfile.write(s.upper())
1377
1378 def __getattr__(self, name):
1379 return getattr(self._outfile, name)
1380
1381Here the ``UpperOut`` class redefines the ``write()`` method to convert the
1382argument string to uppercase before calling the underlying
1383``self.__outfile.write()`` method. All other methods are delegated to the
1384underlying ``self.__outfile`` object. The delegation is accomplished via the
1385``__getattr__`` method; consult :ref:`the language reference <attribute-access>`
1386for more information about controlling attribute access.
1387
1388Note that for more general cases delegation can get trickier. When attributes
1389must be set as well as retrieved, the class must define a :meth:`__setattr__`
1390method too, and it must do so carefully. The basic implementation of
1391:meth:`__setattr__` is roughly equivalent to the following::
1392
1393 class X:
1394 ...
1395 def __setattr__(self, name, value):
1396 self.__dict__[name] = value
1397 ...
1398
1399Most :meth:`__setattr__` implementations must modify ``self.__dict__`` to store
1400local state for self without causing an infinite recursion.
1401
1402
1403How do I call a method defined in a base class from a derived class that overrides it?
1404--------------------------------------------------------------------------------------
1405
Georg Brandl62eaaf62009-12-19 17:51:41 +00001406Use the built-in :func:`super` function::
Georg Brandld7413152009-10-11 21:25:26 +00001407
1408 class Derived(Base):
1409 def meth (self):
1410 super(Derived, self).meth()
1411
Georg Brandl62eaaf62009-12-19 17:51:41 +00001412For version prior to 3.0, you may be using classic classes: For a class
1413definition such as ``class Derived(Base): ...`` you can call method ``meth()``
1414defined in ``Base`` (or one of ``Base``'s base classes) as ``Base.meth(self,
1415arguments...)``. Here, ``Base.meth`` is an unbound method, so you need to
1416provide the ``self`` argument.
Georg Brandld7413152009-10-11 21:25:26 +00001417
1418
1419How can I organize my code to make it easier to change the base class?
1420----------------------------------------------------------------------
1421
1422You could define an alias for the base class, assign the real base class to it
1423before your class definition, and use the alias throughout your class. Then all
1424you have to change is the value assigned to the alias. Incidentally, this trick
1425is also handy if you want to decide dynamically (e.g. depending on availability
1426of resources) which base class to use. Example::
1427
1428 BaseAlias = <real base class>
1429
1430 class Derived(BaseAlias):
1431 def meth(self):
1432 BaseAlias.meth(self)
1433 ...
1434
1435
1436How do I create static class data and static class methods?
1437-----------------------------------------------------------
1438
Georg Brandl62eaaf62009-12-19 17:51:41 +00001439Both static data and static methods (in the sense of C++ or Java) are supported
1440in Python.
Georg Brandld7413152009-10-11 21:25:26 +00001441
1442For static data, simply define a class attribute. To assign a new value to the
1443attribute, you have to explicitly use the class name in the assignment::
1444
1445 class C:
1446 count = 0 # number of times C.__init__ called
1447
1448 def __init__(self):
1449 C.count = C.count + 1
1450
1451 def getcount(self):
1452 return C.count # or return self.count
1453
1454``c.count`` also refers to ``C.count`` for any ``c`` such that ``isinstance(c,
1455C)`` holds, unless overridden by ``c`` itself or by some class on the base-class
1456search path from ``c.__class__`` back to ``C``.
1457
1458Caution: within a method of C, an assignment like ``self.count = 42`` creates a
Georg Brandl62eaaf62009-12-19 17:51:41 +00001459new and unrelated instance named "count" in ``self``'s own dict. Rebinding of a
1460class-static data name must always specify the class whether inside a method or
1461not::
Georg Brandld7413152009-10-11 21:25:26 +00001462
1463 C.count = 314
1464
1465Static methods are possible since Python 2.2::
1466
1467 class C:
1468 def static(arg1, arg2, arg3):
1469 # No 'self' parameter!
1470 ...
1471 static = staticmethod(static)
1472
1473With Python 2.4's decorators, this can also be written as ::
1474
1475 class C:
1476 @staticmethod
1477 def static(arg1, arg2, arg3):
1478 # No 'self' parameter!
1479 ...
1480
1481However, a far more straightforward way to get the effect of a static method is
1482via a simple module-level function::
1483
1484 def getcount():
1485 return C.count
1486
1487If your code is structured so as to define one class (or tightly related class
1488hierarchy) per module, this supplies the desired encapsulation.
1489
1490
1491How can I overload constructors (or methods) in Python?
1492-------------------------------------------------------
1493
1494This answer actually applies to all methods, but the question usually comes up
1495first in the context of constructors.
1496
1497In C++ you'd write
1498
1499.. code-block:: c
1500
1501 class C {
1502 C() { cout << "No arguments\n"; }
1503 C(int i) { cout << "Argument is " << i << "\n"; }
1504 }
1505
1506In Python you have to write a single constructor that catches all cases using
1507default arguments. For example::
1508
1509 class C:
1510 def __init__(self, i=None):
1511 if i is None:
Georg Brandl62eaaf62009-12-19 17:51:41 +00001512 print("No arguments")
Georg Brandld7413152009-10-11 21:25:26 +00001513 else:
Georg Brandl62eaaf62009-12-19 17:51:41 +00001514 print("Argument is", i)
Georg Brandld7413152009-10-11 21:25:26 +00001515
1516This is not entirely equivalent, but close enough in practice.
1517
1518You could also try a variable-length argument list, e.g. ::
1519
1520 def __init__(self, *args):
1521 ...
1522
1523The same approach works for all method definitions.
1524
1525
1526I try to use __spam and I get an error about _SomeClassName__spam.
1527------------------------------------------------------------------
1528
1529Variable names with double leading underscores are "mangled" to provide a simple
1530but effective way to define class private variables. Any identifier of the form
1531``__spam`` (at least two leading underscores, at most one trailing underscore)
1532is textually replaced with ``_classname__spam``, where ``classname`` is the
1533current class name with any leading underscores stripped.
1534
1535This doesn't guarantee privacy: an outside user can still deliberately access
1536the "_classname__spam" attribute, and private values are visible in the object's
1537``__dict__``. Many Python programmers never bother to use private variable
1538names at all.
1539
1540
1541My class defines __del__ but it is not called when I delete the object.
1542-----------------------------------------------------------------------
1543
1544There are several possible reasons for this.
1545
1546The del statement does not necessarily call :meth:`__del__` -- it simply
1547decrements the object's reference count, and if this reaches zero
1548:meth:`__del__` is called.
1549
1550If your data structures contain circular links (e.g. a tree where each child has
1551a parent reference and each parent has a list of children) the reference counts
1552will never go back to zero. Once in a while Python runs an algorithm to detect
1553such cycles, but the garbage collector might run some time after the last
1554reference to your data structure vanishes, so your :meth:`__del__` method may be
1555called at an inconvenient and random time. This is inconvenient if you're trying
1556to reproduce a problem. Worse, the order in which object's :meth:`__del__`
1557methods are executed is arbitrary. You can run :func:`gc.collect` to force a
1558collection, but there *are* pathological cases where objects will never be
1559collected.
1560
1561Despite the cycle collector, it's still a good idea to define an explicit
1562``close()`` method on objects to be called whenever you're done with them. The
1563``close()`` method can then remove attributes that refer to subobjecs. Don't
1564call :meth:`__del__` directly -- :meth:`__del__` should call ``close()`` and
1565``close()`` should make sure that it can be called more than once for the same
1566object.
1567
1568Another way to avoid cyclical references is to use the :mod:`weakref` module,
1569which allows you to point to objects without incrementing their reference count.
1570Tree data structures, for instance, should use weak references for their parent
1571and sibling references (if they need them!).
1572
Georg Brandl62eaaf62009-12-19 17:51:41 +00001573.. XXX relevant for Python 3?
1574
1575 If the object has ever been a local variable in a function that caught an
1576 expression in an except clause, chances are that a reference to the object
1577 still exists in that function's stack frame as contained in the stack trace.
1578 Normally, calling :func:`sys.exc_clear` will take care of this by clearing
1579 the last recorded exception.
Georg Brandld7413152009-10-11 21:25:26 +00001580
1581Finally, if your :meth:`__del__` method raises an exception, a warning message
1582is printed to :data:`sys.stderr`.
1583
1584
1585How do I get a list of all instances of a given class?
1586------------------------------------------------------
1587
1588Python does not keep track of all instances of a class (or of a built-in type).
1589You can program the class's constructor to keep track of all instances by
1590keeping a list of weak references to each instance.
1591
1592
1593Modules
1594=======
1595
1596How do I create a .pyc file?
1597----------------------------
1598
1599When a module is imported for the first time (or when the source is more recent
1600than the current compiled file) a ``.pyc`` file containing the compiled code
1601should be created in the same directory as the ``.py`` file.
1602
1603One reason that a ``.pyc`` file may not be created is permissions problems with
1604the directory. This can happen, for example, if you develop as one user but run
1605as another, such as if you are testing with a web server. Creation of a .pyc
1606file is automatic if you're importing a module and Python has the ability
1607(permissions, free space, etc...) to write the compiled module back to the
1608directory.
1609
1610Running Python on a top level script is not considered an import and no ``.pyc``
1611will be created. For example, if you have a top-level module ``abc.py`` that
1612imports another module ``xyz.py``, when you run abc, ``xyz.pyc`` will be created
1613since xyz is imported, but no ``abc.pyc`` file will be created since ``abc.py``
1614isn't being imported.
1615
1616If you need to create abc.pyc -- that is, to create a .pyc file for a module
1617that is not imported -- you can, using the :mod:`py_compile` and
1618:mod:`compileall` modules.
1619
1620The :mod:`py_compile` module can manually compile any module. One way is to use
1621the ``compile()`` function in that module interactively::
1622
1623 >>> import py_compile
1624 >>> py_compile.compile('abc.py')
1625
1626This will write the ``.pyc`` to the same location as ``abc.py`` (or you can
1627override that with the optional parameter ``cfile``).
1628
1629You can also automatically compile all files in a directory or directories using
1630the :mod:`compileall` module. You can do it from the shell prompt by running
1631``compileall.py`` and providing the path of a directory containing Python files
1632to compile::
1633
1634 python -m compileall .
1635
1636
1637How do I find the current module name?
1638--------------------------------------
1639
1640A module can find out its own module name by looking at the predefined global
1641variable ``__name__``. If this has the value ``'__main__'``, the program is
1642running as a script. Many modules that are usually used by importing them also
1643provide a command-line interface or a self-test, and only execute this code
1644after checking ``__name__``::
1645
1646 def main():
Georg Brandl62eaaf62009-12-19 17:51:41 +00001647 print('Running test...')
Georg Brandld7413152009-10-11 21:25:26 +00001648 ...
1649
1650 if __name__ == '__main__':
1651 main()
1652
1653
1654How can I have modules that mutually import each other?
1655-------------------------------------------------------
1656
1657Suppose you have the following modules:
1658
1659foo.py::
1660
1661 from bar import bar_var
1662 foo_var = 1
1663
1664bar.py::
1665
1666 from foo import foo_var
1667 bar_var = 2
1668
1669The problem is that the interpreter will perform the following steps:
1670
1671* main imports foo
1672* Empty globals for foo are created
1673* foo is compiled and starts executing
1674* foo imports bar
1675* Empty globals for bar are created
1676* bar is compiled and starts executing
1677* bar imports foo (which is a no-op since there already is a module named foo)
1678* bar.foo_var = foo.foo_var
1679
1680The last step fails, because Python isn't done with interpreting ``foo`` yet and
1681the global symbol dictionary for ``foo`` is still empty.
1682
1683The same thing happens when you use ``import foo``, and then try to access
1684``foo.foo_var`` in global code.
1685
1686There are (at least) three possible workarounds for this problem.
1687
1688Guido van Rossum recommends avoiding all uses of ``from <module> import ...``,
1689and placing all code inside functions. Initializations of global variables and
1690class variables should use constants or built-in functions only. This means
1691everything from an imported module is referenced as ``<module>.<name>``.
1692
1693Jim Roskind suggests performing steps in the following order in each module:
1694
1695* exports (globals, functions, and classes that don't need imported base
1696 classes)
1697* ``import`` statements
1698* active code (including globals that are initialized from imported values).
1699
1700van Rossum doesn't like this approach much because the imports appear in a
1701strange place, but it does work.
1702
1703Matthias Urlichs recommends restructuring your code so that the recursive import
1704is not necessary in the first place.
1705
1706These solutions are not mutually exclusive.
1707
1708
1709__import__('x.y.z') returns <module 'x'>; how do I get z?
1710---------------------------------------------------------
1711
1712Try::
1713
1714 __import__('x.y.z').y.z
1715
1716For more realistic situations, you may have to do something like ::
1717
1718 m = __import__(s)
1719 for i in s.split(".")[1:]:
1720 m = getattr(m, i)
1721
1722See :mod:`importlib` for a convenience function called
1723:func:`~importlib.import_module`.
1724
1725
1726
1727When I edit an imported module and reimport it, the changes don't show up. Why does this happen?
1728-------------------------------------------------------------------------------------------------
1729
1730For reasons of efficiency as well as consistency, Python only reads the module
1731file on the first time a module is imported. If it didn't, in a program
1732consisting of many modules where each one imports the same basic module, the
1733basic module would be parsed and re-parsed many times. To force rereading of a
1734changed module, do this::
1735
Georg Brandl62eaaf62009-12-19 17:51:41 +00001736 import imp
Georg Brandld7413152009-10-11 21:25:26 +00001737 import modname
Georg Brandl62eaaf62009-12-19 17:51:41 +00001738 imp.reload(modname)
Georg Brandld7413152009-10-11 21:25:26 +00001739
1740Warning: this technique is not 100% fool-proof. In particular, modules
1741containing statements like ::
1742
1743 from modname import some_objects
1744
1745will continue to work with the old version of the imported objects. If the
1746module contains class definitions, existing class instances will *not* be
1747updated to use the new class definition. This can result in the following
1748paradoxical behaviour:
1749
Georg Brandl62eaaf62009-12-19 17:51:41 +00001750 >>> import imp
Georg Brandld7413152009-10-11 21:25:26 +00001751 >>> import cls
1752 >>> c = cls.C() # Create an instance of C
Georg Brandl62eaaf62009-12-19 17:51:41 +00001753 >>> imp.reload(cls)
1754 <module 'cls' from 'cls.py'>
Georg Brandld7413152009-10-11 21:25:26 +00001755 >>> isinstance(c, cls.C) # isinstance is false?!?
1756 False
1757
Georg Brandl62eaaf62009-12-19 17:51:41 +00001758The nature of the problem is made clear if you print out the "identity" of the
1759class objects:
Georg Brandld7413152009-10-11 21:25:26 +00001760
Georg Brandl62eaaf62009-12-19 17:51:41 +00001761 >>> hex(id(c.__class__))
1762 '0x7352a0'
1763 >>> hex(id(cls.C))
1764 '0x4198d0'