blob: 1e94c3474289c43046e5f671be2e8ea5fb08696b [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
Antoine Pitrou09264b62011-02-05 10:57:17 +0000124`Cython <http://cython.org>`_ and `Pyrex <http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/>`_
125can compile a slightly modified version of Python code into a C extension, and
Antoine Pitrou9cb41df2011-12-03 21:21:36 +0100126can be used on many different platforms. Depending on your code, Cython
127may be able to make it significantly faster than when run by the Python
128interpreter.
Georg Brandld7413152009-10-11 21:25:26 +0000129
130The rest of this answer will discuss various tricks for squeezing a bit more
131speed out of Python code. *Never* apply any optimization tricks unless you know
132you need them, after profiling has indicated that a particular function is the
133heavily executed hot spot in the code. Optimizations almost always make the
134code less clear, and you shouldn't pay the costs of reduced clarity (increased
135development time, greater likelihood of bugs) unless the resulting performance
136benefit is worth it.
137
138There is a page on the wiki devoted to `performance tips
139<http://wiki.python.org/moin/PythonSpeed/PerformanceTips>`_.
140
141Guido van Rossum has written up an anecdote related to optimization at
142http://www.python.org/doc/essays/list2str.html.
143
144One thing to notice is that function and (especially) method calls are rather
145expensive; if you have designed a purely OO interface with lots of tiny
146functions that don't do much more than get or set an instance variable or call
147another method, you might consider using a more direct way such as directly
148accessing instance variables. Also see the standard module :mod:`profile` which
149makes it possible to find out where your program is spending most of its time
150(if you have some patience -- the profiling itself can slow your program down by
151an order of magnitude).
152
153Remember that many standard optimization heuristics you may know from other
154programming experience may well apply to Python. For example it may be faster
155to send output to output devices using larger writes rather than smaller ones in
156order to reduce the overhead of kernel system calls. Thus CGI scripts that
157write all output in "one shot" may be faster than those that write lots of small
158pieces of output.
159
160Also, be sure to use Python's core features where appropriate. For example,
161slicing allows programs to chop up lists and other sequence objects in a single
162tick of the interpreter's mainloop using highly optimized C implementations.
163Thus to get the same effect as::
164
165 L2 = []
Georg Brandle1eef412011-08-25 11:52:26 +0200166 for i in range(3):
Georg Brandld7413152009-10-11 21:25:26 +0000167 L2.append(L1[i])
168
169it is much shorter and far faster to use ::
170
Georg Brandl62eaaf62009-12-19 17:51:41 +0000171 L2 = list(L1[:3]) # "list" is redundant if L1 is a list.
Georg Brandld7413152009-10-11 21:25:26 +0000172
Georg Brandlc4a55fc2010-02-06 18:46:57 +0000173Note that the functionally-oriented built-in functions such as :func:`map`,
174:func:`zip`, and friends can be a convenient accelerator for loops that
175perform a single task. For example to pair the elements of two lists
176together::
Georg Brandld7413152009-10-11 21:25:26 +0000177
Georg Brandl11b63622009-12-20 14:21:27 +0000178 >>> list(zip([1, 2, 3], [4, 5, 6]))
Georg Brandld7413152009-10-11 21:25:26 +0000179 [(1, 4), (2, 5), (3, 6)]
180
181or to compute a number of sines::
182
Georg Brandl62eaaf62009-12-19 17:51:41 +0000183 >>> list(map(math.sin, (1, 2, 3, 4)))
184 [0.841470984808, 0.909297426826, 0.14112000806, -0.756802495308]
Georg Brandld7413152009-10-11 21:25:26 +0000185
186The operation completes very quickly in such cases.
187
Georg Brandl11b63622009-12-20 14:21:27 +0000188Other examples include the ``join()`` and ``split()`` :ref:`methods
189of string objects <string-methods>`.
190
Georg Brandld7413152009-10-11 21:25:26 +0000191For example if s1..s7 are large (10K+) strings then
192``"".join([s1,s2,s3,s4,s5,s6,s7])`` may be far faster than the more obvious
193``s1+s2+s3+s4+s5+s6+s7``, since the "summation" will compute many
194subexpressions, whereas ``join()`` does all the copying in one pass. For
Georg Brandl11b63622009-12-20 14:21:27 +0000195manipulating strings, use the ``replace()`` and the ``format()`` :ref:`methods
196on string objects <string-methods>`. Use regular expressions only when you're
197not dealing with constant string patterns.
Georg Brandld7413152009-10-11 21:25:26 +0000198
Georg Brandlc4a55fc2010-02-06 18:46:57 +0000199Be sure to use the :meth:`list.sort` built-in method to do sorting, and see the
Georg Brandld7413152009-10-11 21:25:26 +0000200`sorting mini-HOWTO <http://wiki.python.org/moin/HowTo/Sorting>`_ for examples
201of moderately advanced usage. :meth:`list.sort` beats other techniques for
202sorting in all but the most extreme circumstances.
203
204Another common trick is to "push loops into functions or methods." For example
205suppose you have a program that runs slowly and you use the profiler to
206determine that a Python function ``ff()`` is being called lots of times. If you
Georg Brandl62eaaf62009-12-19 17:51:41 +0000207notice that ``ff()``::
Georg Brandld7413152009-10-11 21:25:26 +0000208
209 def ff(x):
210 ... # do something with x computing result...
211 return result
212
213tends to be called in loops like::
214
215 list = map(ff, oldlist)
216
217or::
218
219 for x in sequence:
220 value = ff(x)
221 ... # do something with value...
222
223then you can often eliminate function call overhead by rewriting ``ff()`` to::
224
225 def ffseq(seq):
226 resultseq = []
227 for x in seq:
228 ... # do something with x computing result...
229 resultseq.append(result)
230 return resultseq
231
232and rewrite the two examples to ``list = ffseq(oldlist)`` and to::
233
234 for value in ffseq(sequence):
235 ... # do something with value...
236
237Single calls to ``ff(x)`` translate to ``ffseq([x])[0]`` with little penalty.
238Of course this technique is not always appropriate and there are other variants
239which you can figure out.
240
241You can gain some performance by explicitly storing the results of a function or
242method lookup into a local variable. A loop like::
243
244 for key in token:
245 dict[key] = dict.get(key, 0) + 1
246
247resolves ``dict.get`` every iteration. If the method isn't going to change, a
248slightly faster implementation is::
249
250 dict_get = dict.get # look up the method once
251 for key in token:
252 dict[key] = dict_get(key, 0) + 1
253
254Default arguments can be used to determine values once, at compile time instead
255of at run time. This can only be done for functions or objects which will not
256be changed during program execution, such as replacing ::
257
258 def degree_sin(deg):
259 return math.sin(deg * math.pi / 180.0)
260
261with ::
262
263 def degree_sin(deg, factor=math.pi/180.0, sin=math.sin):
264 return sin(deg * factor)
265
266Because this trick uses default arguments for terms which should not be changed,
267it should only be used when you are not concerned with presenting a possibly
268confusing API to your users.
269
270
271Core Language
272=============
273
R. David Murrayc04a6942009-11-14 22:21:32 +0000274Why am I getting an UnboundLocalError when the variable has a value?
275--------------------------------------------------------------------
Georg Brandld7413152009-10-11 21:25:26 +0000276
R. David Murrayc04a6942009-11-14 22:21:32 +0000277It can be a surprise to get the UnboundLocalError in previously working
278code when it is modified by adding an assignment statement somewhere in
279the body of a function.
Georg Brandld7413152009-10-11 21:25:26 +0000280
R. David Murrayc04a6942009-11-14 22:21:32 +0000281This code:
Georg Brandld7413152009-10-11 21:25:26 +0000282
R. David Murrayc04a6942009-11-14 22:21:32 +0000283 >>> x = 10
284 >>> def bar():
285 ... print(x)
286 >>> bar()
287 10
Georg Brandld7413152009-10-11 21:25:26 +0000288
R. David Murrayc04a6942009-11-14 22:21:32 +0000289works, but this code:
Georg Brandld7413152009-10-11 21:25:26 +0000290
R. David Murrayc04a6942009-11-14 22:21:32 +0000291 >>> x = 10
292 >>> def foo():
293 ... print(x)
294 ... x += 1
Georg Brandld7413152009-10-11 21:25:26 +0000295
R. David Murrayc04a6942009-11-14 22:21:32 +0000296results in an UnboundLocalError:
Georg Brandld7413152009-10-11 21:25:26 +0000297
R. David Murrayc04a6942009-11-14 22:21:32 +0000298 >>> foo()
299 Traceback (most recent call last):
300 ...
301 UnboundLocalError: local variable 'x' referenced before assignment
302
303This is because when you make an assignment to a variable in a scope, that
304variable becomes local to that scope and shadows any similarly named variable
305in the outer scope. Since the last statement in foo assigns a new value to
306``x``, the compiler recognizes it as a local variable. Consequently when the
R. David Murray18163c32009-11-14 22:27:22 +0000307earlier ``print(x)`` attempts to print the uninitialized local variable and
R. David Murrayc04a6942009-11-14 22:21:32 +0000308an error results.
309
310In the example above you can access the outer scope variable by declaring it
311global:
312
313 >>> x = 10
314 >>> def foobar():
315 ... global x
316 ... print(x)
317 ... x += 1
318 >>> foobar()
319 10
320
321This explicit declaration is required in order to remind you that (unlike the
322superficially analogous situation with class and instance variables) you are
323actually modifying the value of the variable in the outer scope:
324
325 >>> print(x)
326 11
327
328You can do a similar thing in a nested scope using the :keyword:`nonlocal`
329keyword:
330
331 >>> def foo():
332 ... x = 10
333 ... def bar():
334 ... nonlocal x
335 ... print(x)
336 ... x += 1
337 ... bar()
338 ... print(x)
339 >>> foo()
340 10
341 11
Georg Brandld7413152009-10-11 21:25:26 +0000342
343
344What are the rules for local and global variables in Python?
345------------------------------------------------------------
346
347In Python, variables that are only referenced inside a function are implicitly
348global. If a variable is assigned a new value anywhere within the function's
349body, it's assumed to be a local. If a variable is ever assigned a new value
350inside the function, the variable is implicitly local, and you need to
351explicitly declare it as 'global'.
352
353Though a bit surprising at first, a moment's consideration explains this. On
354one hand, requiring :keyword:`global` for assigned variables provides a bar
355against unintended side-effects. On the other hand, if ``global`` was required
356for all global references, you'd be using ``global`` all the time. You'd have
Georg Brandlc4a55fc2010-02-06 18:46:57 +0000357to declare as global every reference to a built-in function or to a component of
Georg Brandld7413152009-10-11 21:25:26 +0000358an imported module. This clutter would defeat the usefulness of the ``global``
359declaration for identifying side-effects.
360
361
362How do I share global variables across modules?
363------------------------------------------------
364
365The canonical way to share information across modules within a single program is
366to create a special module (often called config or cfg). Just import the config
367module in all modules of your application; the module then becomes available as
368a global name. Because there is only one instance of each module, any changes
369made to the module object get reflected everywhere. For example:
370
371config.py::
372
373 x = 0 # Default value of the 'x' configuration setting
374
375mod.py::
376
377 import config
378 config.x = 1
379
380main.py::
381
382 import config
383 import mod
Georg Brandl62eaaf62009-12-19 17:51:41 +0000384 print(config.x)
Georg Brandld7413152009-10-11 21:25:26 +0000385
386Note that using a module is also the basis for implementing the Singleton design
387pattern, for the same reason.
388
389
390What are the "best practices" for using import in a module?
391-----------------------------------------------------------
392
393In general, don't use ``from modulename import *``. Doing so clutters the
394importer's namespace. Some people avoid this idiom even with the few modules
395that were designed to be imported in this manner. Modules designed in this
Georg Brandld404fa62009-10-13 16:55:12 +0000396manner include :mod:`tkinter`, and :mod:`threading`.
Georg Brandld7413152009-10-11 21:25:26 +0000397
398Import modules at the top of a file. Doing so makes it clear what other modules
399your code requires and avoids questions of whether the module name is in scope.
400Using one import per line makes it easy to add and delete module imports, but
401using multiple imports per line uses less screen space.
402
403It's good practice if you import modules in the following order:
404
Georg Brandl62eaaf62009-12-19 17:51:41 +00004051. standard library modules -- e.g. ``sys``, ``os``, ``getopt``, ``re``
Georg Brandld7413152009-10-11 21:25:26 +00004062. third-party library modules (anything installed in Python's site-packages
407 directory) -- e.g. mx.DateTime, ZODB, PIL.Image, etc.
4083. locally-developed modules
409
410Never use relative package imports. If you're writing code that's in the
411``package.sub.m1`` module and want to import ``package.sub.m2``, do not just
Georg Brandl11b63622009-12-20 14:21:27 +0000412write ``from . import m2``, even though it's legal. Write ``from package.sub
413import m2`` instead. See :pep:`328` for details.
Georg Brandld7413152009-10-11 21:25:26 +0000414
415It is sometimes necessary to move imports to a function or class to avoid
416problems with circular imports. Gordon McMillan says:
417
418 Circular imports are fine where both modules use the "import <module>" form
419 of import. They fail when the 2nd module wants to grab a name out of the
420 first ("from module import name") and the import is at the top level. That's
421 because names in the 1st are not yet available, because the first module is
422 busy importing the 2nd.
423
424In this case, if the second module is only used in one function, then the import
425can easily be moved into that function. By the time the import is called, the
426first module will have finished initializing, and the second module can do its
427import.
428
429It may also be necessary to move imports out of the top level of code if some of
430the modules are platform-specific. In that case, it may not even be possible to
431import all of the modules at the top of the file. In this case, importing the
432correct modules in the corresponding platform-specific code is a good option.
433
434Only move imports into a local scope, such as inside a function definition, if
435it's necessary to solve a problem such as avoiding a circular import or are
436trying to reduce the initialization time of a module. This technique is
437especially helpful if many of the imports are unnecessary depending on how the
438program executes. You may also want to move imports into a function if the
439modules are only ever used in that function. Note that loading a module the
440first time may be expensive because of the one time initialization of the
441module, but loading a module multiple times is virtually free, costing only a
442couple of dictionary lookups. Even if the module name has gone out of scope,
443the module is probably available in :data:`sys.modules`.
444
445If only instances of a specific class use a module, then it is reasonable to
446import the module in the class's ``__init__`` method and then assign the module
447to an instance variable so that the module is always available (via that
448instance variable) during the life of the object. Note that to delay an import
449until the class is instantiated, the import must be inside a method. Putting
450the import inside the class but outside of any method still causes the import to
451occur when the module is initialized.
452
453
454How can I pass optional or keyword parameters from one function to another?
455---------------------------------------------------------------------------
456
457Collect the arguments using the ``*`` and ``**`` specifiers in the function's
458parameter list; this gives you the positional arguments as a tuple and the
459keyword arguments as a dictionary. You can then pass these arguments when
460calling another function by using ``*`` and ``**``::
461
462 def f(x, *args, **kwargs):
463 ...
464 kwargs['width'] = '14.3c'
465 ...
466 g(x, *args, **kwargs)
467
Georg Brandld7413152009-10-11 21:25:26 +0000468
469How do I write a function with output parameters (call by reference)?
470---------------------------------------------------------------------
471
472Remember that arguments are passed by assignment in Python. Since assignment
473just creates references to objects, there's no alias between an argument name in
474the caller and callee, and so no call-by-reference per se. You can achieve the
475desired effect in a number of ways.
476
4771) By returning a tuple of the results::
478
479 def func2(a, b):
480 a = 'new-value' # a and b are local names
481 b = b + 1 # assigned to new objects
482 return a, b # return new values
483
484 x, y = 'old-value', 99
485 x, y = func2(x, y)
Georg Brandl62eaaf62009-12-19 17:51:41 +0000486 print(x, y) # output: new-value 100
Georg Brandld7413152009-10-11 21:25:26 +0000487
488 This is almost always the clearest solution.
489
4902) By using global variables. This isn't thread-safe, and is not recommended.
491
4923) By passing a mutable (changeable in-place) object::
493
494 def func1(a):
495 a[0] = 'new-value' # 'a' references a mutable list
496 a[1] = a[1] + 1 # changes a shared object
497
498 args = ['old-value', 99]
499 func1(args)
Georg Brandl62eaaf62009-12-19 17:51:41 +0000500 print(args[0], args[1]) # output: new-value 100
Georg Brandld7413152009-10-11 21:25:26 +0000501
5024) By passing in a dictionary that gets mutated::
503
504 def func3(args):
505 args['a'] = 'new-value' # args is a mutable dictionary
506 args['b'] = args['b'] + 1 # change it in-place
507
508 args = {'a':' old-value', 'b': 99}
509 func3(args)
Georg Brandl62eaaf62009-12-19 17:51:41 +0000510 print(args['a'], args['b'])
Georg Brandld7413152009-10-11 21:25:26 +0000511
5125) Or bundle up values in a class instance::
513
514 class callByRef:
515 def __init__(self, **args):
516 for (key, value) in args.items():
517 setattr(self, key, value)
518
519 def func4(args):
520 args.a = 'new-value' # args is a mutable callByRef
521 args.b = args.b + 1 # change object in-place
522
523 args = callByRef(a='old-value', b=99)
524 func4(args)
Georg Brandl62eaaf62009-12-19 17:51:41 +0000525 print(args.a, args.b)
Georg Brandld7413152009-10-11 21:25:26 +0000526
527
528 There's almost never a good reason to get this complicated.
529
530Your best choice is to return a tuple containing the multiple results.
531
532
533How do you make a higher order function in Python?
534--------------------------------------------------
535
536You have two choices: you can use nested scopes or you can use callable objects.
537For example, suppose you wanted to define ``linear(a,b)`` which returns a
538function ``f(x)`` that computes the value ``a*x+b``. Using nested scopes::
539
540 def linear(a, b):
541 def result(x):
542 return a * x + b
543 return result
544
545Or using a callable object::
546
547 class linear:
548
549 def __init__(self, a, b):
550 self.a, self.b = a, b
551
552 def __call__(self, x):
553 return self.a * x + self.b
554
555In both cases, ::
556
557 taxes = linear(0.3, 2)
558
559gives a callable object where ``taxes(10e6) == 0.3 * 10e6 + 2``.
560
561The callable object approach has the disadvantage that it is a bit slower and
562results in slightly longer code. However, note that a collection of callables
563can share their signature via inheritance::
564
565 class exponential(linear):
566 # __init__ inherited
567 def __call__(self, x):
568 return self.a * (x ** self.b)
569
570Object can encapsulate state for several methods::
571
572 class counter:
573
574 value = 0
575
576 def set(self, x):
577 self.value = x
578
579 def up(self):
580 self.value = self.value + 1
581
582 def down(self):
583 self.value = self.value - 1
584
585 count = counter()
586 inc, dec, reset = count.up, count.down, count.set
587
588Here ``inc()``, ``dec()`` and ``reset()`` act like functions which share the
589same counting variable.
590
591
592How do I copy an object in Python?
593----------------------------------
594
595In general, try :func:`copy.copy` or :func:`copy.deepcopy` for the general case.
596Not all objects can be copied, but most can.
597
598Some objects can be copied more easily. Dictionaries have a :meth:`~dict.copy`
599method::
600
601 newdict = olddict.copy()
602
603Sequences can be copied by slicing::
604
605 new_l = l[:]
606
607
608How can I find the methods or attributes of an object?
609------------------------------------------------------
610
611For an instance x of a user-defined class, ``dir(x)`` returns an alphabetized
612list of the names containing the instance attributes and methods and attributes
613defined by its class.
614
615
616How can my code discover the name of an object?
617-----------------------------------------------
618
619Generally speaking, it can't, because objects don't really have names.
620Essentially, assignment always binds a name to a value; The same is true of
621``def`` and ``class`` statements, but in that case the value is a
622callable. Consider the following code::
623
624 class A:
625 pass
626
627 B = A
628
629 a = B()
630 b = a
Georg Brandl62eaaf62009-12-19 17:51:41 +0000631 print(b)
632 <__main__.A object at 0x16D07CC>
633 print(a)
634 <__main__.A object at 0x16D07CC>
Georg Brandld7413152009-10-11 21:25:26 +0000635
636Arguably the class has a name: even though it is bound to two names and invoked
637through the name B the created instance is still reported as an instance of
638class A. However, it is impossible to say whether the instance's name is a or
639b, since both names are bound to the same value.
640
641Generally speaking it should not be necessary for your code to "know the names"
642of particular values. Unless you are deliberately writing introspective
643programs, this is usually an indication that a change of approach might be
644beneficial.
645
646In comp.lang.python, Fredrik Lundh once gave an excellent analogy in answer to
647this question:
648
649 The same way as you get the name of that cat you found on your porch: the cat
650 (object) itself cannot tell you its name, and it doesn't really care -- so
651 the only way to find out what it's called is to ask all your neighbours
652 (namespaces) if it's their cat (object)...
653
654 ....and don't be surprised if you'll find that it's known by many names, or
655 no name at all!
656
657
658What's up with the comma operator's precedence?
659-----------------------------------------------
660
661Comma is not an operator in Python. Consider this session::
662
663 >>> "a" in "b", "a"
Georg Brandl62eaaf62009-12-19 17:51:41 +0000664 (False, 'a')
Georg Brandld7413152009-10-11 21:25:26 +0000665
666Since the comma is not an operator, but a separator between expressions the
667above is evaluated as if you had entered::
668
669 >>> ("a" in "b"), "a"
670
671not::
672
Georg Brandl62eaaf62009-12-19 17:51:41 +0000673 >>> "a" in ("b", "a")
Georg Brandld7413152009-10-11 21:25:26 +0000674
675The same is true of the various assignment operators (``=``, ``+=`` etc). They
676are not truly operators but syntactic delimiters in assignment statements.
677
678
679Is there an equivalent of C's "?:" ternary operator?
680----------------------------------------------------
681
Antoine Pitrouc5b266e2011-12-03 22:11:11 +0100682Yes, there is. The syntax is as follows::
Georg Brandld7413152009-10-11 21:25:26 +0000683
684 [on_true] if [expression] else [on_false]
685
686 x, y = 50, 25
Georg Brandld7413152009-10-11 21:25:26 +0000687 small = x if x < y else y
688
Antoine Pitrouc5b266e2011-12-03 22:11:11 +0100689Before this syntax was introduced in Python 2.5, a common idiom was to use
690logical operators::
Georg Brandld7413152009-10-11 21:25:26 +0000691
Antoine Pitrouc5b266e2011-12-03 22:11:11 +0100692 [expression] and [on_true] or [on_false]
Georg Brandld7413152009-10-11 21:25:26 +0000693
Antoine Pitrouc5b266e2011-12-03 22:11:11 +0100694However, this idiom is unsafe, as it can give wrong results when *on_true*
695has a false boolean value. Therefore, it is always better to use
696the ``... if ... else ...`` form.
Georg Brandld7413152009-10-11 21:25:26 +0000697
698
699Is it possible to write obfuscated one-liners in Python?
700--------------------------------------------------------
701
702Yes. Usually this is done by nesting :keyword:`lambda` within
703:keyword:`lambda`. See the following three examples, due to Ulf Bartelt::
704
Georg Brandl62eaaf62009-12-19 17:51:41 +0000705 from functools import reduce
706
Georg Brandld7413152009-10-11 21:25:26 +0000707 # Primes < 1000
Georg Brandl62eaaf62009-12-19 17:51:41 +0000708 print(list(filter(None,map(lambda y:y*reduce(lambda x,y:x*y!=0,
709 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 +0000710
711 # First 10 Fibonacci numbers
Georg Brandl62eaaf62009-12-19 17:51:41 +0000712 print(list(map(lambda x,f=lambda x,f:(f(x-1,f)+f(x-2,f)) if x>1 else 1:
713 f(x,f), range(10))))
Georg Brandld7413152009-10-11 21:25:26 +0000714
715 # Mandelbrot set
Georg Brandl62eaaf62009-12-19 17:51:41 +0000716 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 +0000717 Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,Sy=Sy,L=lambda yc,Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,i=IM,
718 Sx=Sx,Sy=Sy:reduce(lambda x,y:x+y,map(lambda x,xc=Ru,yc=yc,Ru=Ru,Ro=Ro,
719 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
720 >=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(
721 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 +0000722 ))))(-2.1, 0.7, -1.2, 1.2, 30, 80, 24))
Georg Brandld7413152009-10-11 21:25:26 +0000723 # \___ ___/ \___ ___/ | | |__ lines on screen
724 # V V | |______ columns on screen
725 # | | |__________ maximum of "iterations"
726 # | |_________________ range on y axis
727 # |____________________________ range on x axis
728
729Don't try this at home, kids!
730
731
732Numbers and strings
733===================
734
735How do I specify hexadecimal and octal integers?
736------------------------------------------------
737
Georg Brandl62eaaf62009-12-19 17:51:41 +0000738To specify an octal digit, precede the octal value with a zero, and then a lower
739or uppercase "o". For example, to set the variable "a" to the octal value "10"
740(8 in decimal), type::
Georg Brandld7413152009-10-11 21:25:26 +0000741
Georg Brandl62eaaf62009-12-19 17:51:41 +0000742 >>> a = 0o10
Georg Brandld7413152009-10-11 21:25:26 +0000743 >>> a
744 8
745
746Hexadecimal is just as easy. Simply precede the hexadecimal number with a zero,
747and then a lower or uppercase "x". Hexadecimal digits can be specified in lower
748or uppercase. For example, in the Python interpreter::
749
750 >>> a = 0xa5
751 >>> a
752 165
753 >>> b = 0XB2
754 >>> b
755 178
756
757
Georg Brandl62eaaf62009-12-19 17:51:41 +0000758Why does -22 // 10 return -3?
759-----------------------------
Georg Brandld7413152009-10-11 21:25:26 +0000760
761It's primarily driven by the desire that ``i % j`` have the same sign as ``j``.
762If you want that, and also want::
763
Georg Brandl62eaaf62009-12-19 17:51:41 +0000764 i == (i // j) * j + (i % j)
Georg Brandld7413152009-10-11 21:25:26 +0000765
766then integer division has to return the floor. C also requires that identity to
Georg Brandl62eaaf62009-12-19 17:51:41 +0000767hold, and then compilers that truncate ``i // j`` need to make ``i % j`` have
768the same sign as ``i``.
Georg Brandld7413152009-10-11 21:25:26 +0000769
770There are few real use cases for ``i % j`` when ``j`` is negative. When ``j``
771is positive, there are many, and in virtually all of them it's more useful for
772``i % j`` to be ``>= 0``. If the clock says 10 now, what did it say 200 hours
773ago? ``-190 % 12 == 2`` is useful; ``-190 % 12 == -10`` is a bug waiting to
774bite.
775
776
777How do I convert a string to a number?
778--------------------------------------
779
780For integers, use the built-in :func:`int` type constructor, e.g. ``int('144')
781== 144``. Similarly, :func:`float` converts to floating-point,
782e.g. ``float('144') == 144.0``.
783
784By default, these interpret the number as decimal, so that ``int('0144') ==
785144`` and ``int('0x144')`` raises :exc:`ValueError`. ``int(string, base)`` takes
786the base to convert from as a second optional argument, so ``int('0x144', 16) ==
787324``. If the base is specified as 0, the number is interpreted using Python's
788rules: a leading '0' indicates octal, and '0x' indicates a hex number.
789
790Do not use the built-in function :func:`eval` if all you need is to convert
791strings to numbers. :func:`eval` will be significantly slower and it presents a
792security risk: someone could pass you a Python expression that might have
793unwanted side effects. For example, someone could pass
794``__import__('os').system("rm -rf $HOME")`` which would erase your home
795directory.
796
797:func:`eval` also has the effect of interpreting numbers as Python expressions,
Georg Brandl62eaaf62009-12-19 17:51:41 +0000798so that e.g. ``eval('09')`` gives a syntax error because Python does not allow
799leading '0' in a decimal number (except '0').
Georg Brandld7413152009-10-11 21:25:26 +0000800
801
802How do I convert a number to a string?
803--------------------------------------
804
805To convert, e.g., the number 144 to the string '144', use the built-in type
806constructor :func:`str`. If you want a hexadecimal or octal representation, use
Georg Brandl62eaaf62009-12-19 17:51:41 +0000807the built-in functions :func:`hex` or :func:`oct`. For fancy formatting, see
808the :ref:`string-formatting` section, e.g. ``"{:04d}".format(144)`` yields
Georg Brandl11b63622009-12-20 14:21:27 +0000809``'0144'`` and ``"{:.3f}".format(1/3)`` yields ``'0.333'``.
Georg Brandld7413152009-10-11 21:25:26 +0000810
811
812How do I modify a string in place?
813----------------------------------
814
Antoine Pitrouc5b266e2011-12-03 22:11:11 +0100815You can't, because strings are immutable. In most situations, you should
816simply construct a new string from the various parts you want to assemble
817it from. However, if you need an object with the ability to modify in-place
818unicode data, try using a :class:`io.StringIO` object or the :mod:`array`
819module::
Georg Brandld7413152009-10-11 21:25:26 +0000820
821 >>> s = "Hello, world"
Antoine Pitrouc5b266e2011-12-03 22:11:11 +0100822 >>> sio = io.StringIO(s)
823 >>> sio.getvalue()
824 'Hello, world'
825 >>> sio.seek(7)
826 7
827 >>> sio.write("there!")
828 6
829 >>> sio.getvalue()
Georg Brandld7413152009-10-11 21:25:26 +0000830 'Hello, there!'
831
832 >>> import array
Georg Brandl62eaaf62009-12-19 17:51:41 +0000833 >>> a = array.array('u', s)
834 >>> print(a)
835 array('u', 'Hello, world')
836 >>> a[0] = 'y'
837 >>> print(a)
838 array('u', 'yello world')
839 >>> a.tounicode()
Georg Brandld7413152009-10-11 21:25:26 +0000840 'yello, world'
841
842
843How do I use strings to call functions/methods?
844-----------------------------------------------
845
846There are various techniques.
847
848* The best is to use a dictionary that maps strings to functions. The primary
849 advantage of this technique is that the strings do not need to match the names
850 of the functions. This is also the primary technique used to emulate a case
851 construct::
852
853 def a():
854 pass
855
856 def b():
857 pass
858
859 dispatch = {'go': a, 'stop': b} # Note lack of parens for funcs
860
861 dispatch[get_input()]() # Note trailing parens to call function
862
863* Use the built-in function :func:`getattr`::
864
865 import foo
866 getattr(foo, 'bar')()
867
868 Note that :func:`getattr` works on any object, including classes, class
869 instances, modules, and so on.
870
871 This is used in several places in the standard library, like this::
872
873 class Foo:
874 def do_foo(self):
875 ...
876
877 def do_bar(self):
878 ...
879
880 f = getattr(foo_instance, 'do_' + opname)
881 f()
882
883
884* Use :func:`locals` or :func:`eval` to resolve the function name::
885
886 def myFunc():
Georg Brandl62eaaf62009-12-19 17:51:41 +0000887 print("hello")
Georg Brandld7413152009-10-11 21:25:26 +0000888
889 fname = "myFunc"
890
891 f = locals()[fname]
892 f()
893
894 f = eval(fname)
895 f()
896
897 Note: Using :func:`eval` is slow and dangerous. If you don't have absolute
898 control over the contents of the string, someone could pass a string that
899 resulted in an arbitrary function being executed.
900
901Is there an equivalent to Perl's chomp() for removing trailing newlines from strings?
902-------------------------------------------------------------------------------------
903
904Starting with Python 2.2, you can use ``S.rstrip("\r\n")`` to remove all
Georg Brandl6faee4e2010-09-21 14:48:28 +0000905occurrences of any line terminator from the end of the string ``S`` without
Georg Brandld7413152009-10-11 21:25:26 +0000906removing other trailing whitespace. If the string ``S`` represents more than
907one line, with several empty lines at the end, the line terminators for all the
908blank lines will be removed::
909
910 >>> lines = ("line 1 \r\n"
911 ... "\r\n"
912 ... "\r\n")
913 >>> lines.rstrip("\n\r")
Georg Brandl62eaaf62009-12-19 17:51:41 +0000914 'line 1 '
Georg Brandld7413152009-10-11 21:25:26 +0000915
916Since this is typically only desired when reading text one line at a time, using
917``S.rstrip()`` this way works well.
918
Georg Brandl62eaaf62009-12-19 17:51:41 +0000919For older versions of Python, there are two partial substitutes:
Georg Brandld7413152009-10-11 21:25:26 +0000920
921- If you want to remove all trailing whitespace, use the ``rstrip()`` method of
922 string objects. This removes all trailing whitespace, not just a single
923 newline.
924
925- Otherwise, if there is only one line in the string ``S``, use
926 ``S.splitlines()[0]``.
927
928
929Is there a scanf() or sscanf() equivalent?
930------------------------------------------
931
932Not as such.
933
934For simple input parsing, the easiest approach is usually to split the line into
935whitespace-delimited words using the :meth:`~str.split` method of string objects
936and then convert decimal strings to numeric values using :func:`int` or
937:func:`float`. ``split()`` supports an optional "sep" parameter which is useful
938if the line uses something other than whitespace as a separator.
939
Brian Curtin5a7a52f2010-09-23 13:45:21 +0000940For more complicated input parsing, regular expressions are more powerful
Georg Brandl60203b42010-10-06 10:11:56 +0000941than C's :c:func:`sscanf` and better suited for the task.
Georg Brandld7413152009-10-11 21:25:26 +0000942
943
Georg Brandl62eaaf62009-12-19 17:51:41 +0000944What does 'UnicodeDecodeError' or 'UnicodeEncodeError' error mean?
945-------------------------------------------------------------------
Georg Brandld7413152009-10-11 21:25:26 +0000946
Georg Brandl62eaaf62009-12-19 17:51:41 +0000947See the :ref:`unicode-howto`.
Georg Brandld7413152009-10-11 21:25:26 +0000948
949
Antoine Pitroufd9ebd42011-11-25 16:33:53 +0100950What is the most efficient way to concatenate many strings together?
951--------------------------------------------------------------------
952
953:class:`str` and :class:`bytes` objects are immutable, therefore concatenating
954many strings together is inefficient as each concatenation creates a new
955object. In the general case, the total runtime cost is quadratic in the
956total string length.
957
958To accumulate many :class:`str` objects, the recommended idiom is to place
959them into a list and call :meth:`str.join` at the end::
960
961 chunks = []
962 for s in my_strings:
963 chunks.append(s)
964 result = ''.join(chunks)
965
966(another reasonably efficient idiom is to use :class:`io.StringIO`)
967
968To accumulate many :class:`bytes` objects, the recommended idiom is to extend
969a :class:`bytearray` object using in-place concatenation (the ``+=`` operator)::
970
971 result = bytearray()
972 for b in my_bytes_objects:
973 result += b
974
975
Georg Brandld7413152009-10-11 21:25:26 +0000976Sequences (Tuples/Lists)
977========================
978
979How do I convert between tuples and lists?
980------------------------------------------
981
982The type constructor ``tuple(seq)`` converts any sequence (actually, any
983iterable) into a tuple with the same items in the same order.
984
985For example, ``tuple([1, 2, 3])`` yields ``(1, 2, 3)`` and ``tuple('abc')``
986yields ``('a', 'b', 'c')``. If the argument is a tuple, it does not make a copy
987but returns the same object, so it is cheap to call :func:`tuple` when you
988aren't sure that an object is already a tuple.
989
990The type constructor ``list(seq)`` converts any sequence or iterable into a list
991with the same items in the same order. For example, ``list((1, 2, 3))`` yields
992``[1, 2, 3]`` and ``list('abc')`` yields ``['a', 'b', 'c']``. If the argument
993is a list, it makes a copy just like ``seq[:]`` would.
994
995
996What's a negative index?
997------------------------
998
999Python sequences are indexed with positive numbers and negative numbers. For
1000positive numbers 0 is the first index 1 is the second index and so forth. For
1001negative indices -1 is the last index and -2 is the penultimate (next to last)
1002index and so forth. Think of ``seq[-n]`` as the same as ``seq[len(seq)-n]``.
1003
1004Using negative indices can be very convenient. For example ``S[:-1]`` is all of
1005the string except for its last character, which is useful for removing the
1006trailing newline from a string.
1007
1008
1009How do I iterate over a sequence in reverse order?
1010--------------------------------------------------
1011
Georg Brandlc4a55fc2010-02-06 18:46:57 +00001012Use the :func:`reversed` built-in function, which is new in Python 2.4::
Georg Brandld7413152009-10-11 21:25:26 +00001013
1014 for x in reversed(sequence):
1015 ... # do something with x...
1016
1017This won't touch your original sequence, but build a new copy with reversed
1018order to iterate over.
1019
1020With Python 2.3, you can use an extended slice syntax::
1021
1022 for x in sequence[::-1]:
1023 ... # do something with x...
1024
1025
1026How do you remove duplicates from a list?
1027-----------------------------------------
1028
1029See the Python Cookbook for a long discussion of many ways to do this:
1030
1031 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52560
1032
1033If you don't mind reordering the list, sort it and then scan from the end of the
1034list, deleting duplicates as you go::
1035
Georg Brandl62eaaf62009-12-19 17:51:41 +00001036 if mylist:
1037 mylist.sort()
1038 last = mylist[-1]
1039 for i in range(len(mylist)-2, -1, -1):
1040 if last == mylist[i]:
1041 del mylist[i]
Georg Brandld7413152009-10-11 21:25:26 +00001042 else:
Georg Brandl62eaaf62009-12-19 17:51:41 +00001043 last = mylist[i]
Georg Brandld7413152009-10-11 21:25:26 +00001044
1045If all elements of the list may be used as dictionary keys (i.e. they are all
1046hashable) this is often faster ::
1047
1048 d = {}
Georg Brandl62eaaf62009-12-19 17:51:41 +00001049 for x in mylist:
1050 d[x] = 1
1051 mylist = list(d.keys())
Georg Brandld7413152009-10-11 21:25:26 +00001052
1053In Python 2.5 and later, the following is possible instead::
1054
Georg Brandl62eaaf62009-12-19 17:51:41 +00001055 mylist = list(set(mylist))
Georg Brandld7413152009-10-11 21:25:26 +00001056
1057This converts the list into a set, thereby removing duplicates, and then back
1058into a list.
1059
1060
1061How do you make an array in Python?
1062-----------------------------------
1063
1064Use a list::
1065
1066 ["this", 1, "is", "an", "array"]
1067
1068Lists are equivalent to C or Pascal arrays in their time complexity; the primary
1069difference is that a Python list can contain objects of many different types.
1070
1071The ``array`` module also provides methods for creating arrays of fixed types
1072with compact representations, but they are slower to index than lists. Also
1073note that the Numeric extensions and others define array-like structures with
1074various characteristics as well.
1075
1076To get Lisp-style linked lists, you can emulate cons cells using tuples::
1077
1078 lisp_list = ("like", ("this", ("example", None) ) )
1079
1080If mutability is desired, you could use lists instead of tuples. Here the
1081analogue of lisp car is ``lisp_list[0]`` and the analogue of cdr is
1082``lisp_list[1]``. Only do this if you're sure you really need to, because it's
1083usually a lot slower than using Python lists.
1084
1085
1086How do I create a multidimensional list?
1087----------------------------------------
1088
1089You probably tried to make a multidimensional array like this::
1090
1091 A = [[None] * 2] * 3
1092
1093This looks correct if you print it::
1094
1095 >>> A
1096 [[None, None], [None, None], [None, None]]
1097
1098But when you assign a value, it shows up in multiple places:
1099
1100 >>> A[0][0] = 5
1101 >>> A
1102 [[5, None], [5, None], [5, None]]
1103
1104The reason is that replicating a list with ``*`` doesn't create copies, it only
1105creates references to the existing objects. The ``*3`` creates a list
1106containing 3 references to the same list of length two. Changes to one row will
1107show in all rows, which is almost certainly not what you want.
1108
1109The suggested approach is to create a list of the desired length first and then
1110fill in each element with a newly created list::
1111
1112 A = [None] * 3
1113 for i in range(3):
1114 A[i] = [None] * 2
1115
1116This generates a list containing 3 different lists of length two. You can also
1117use a list comprehension::
1118
1119 w, h = 2, 3
1120 A = [[None] * w for i in range(h)]
1121
1122Or, you can use an extension that provides a matrix datatype; `Numeric Python
Georg Brandl495f7b52009-10-27 15:28:25 +00001123<http://numpy.scipy.org/>`_ is the best known.
Georg Brandld7413152009-10-11 21:25:26 +00001124
1125
1126How do I apply a method to a sequence of objects?
1127-------------------------------------------------
1128
1129Use a list comprehension::
1130
Georg Brandl62eaaf62009-12-19 17:51:41 +00001131 result = [obj.method() for obj in mylist]
Georg Brandld7413152009-10-11 21:25:26 +00001132
1133
1134Dictionaries
1135============
1136
1137How can I get a dictionary to display its keys in a consistent order?
1138---------------------------------------------------------------------
1139
1140You can't. Dictionaries store their keys in an unpredictable order, so the
1141display order of a dictionary's elements will be similarly unpredictable.
1142
1143This can be frustrating if you want to save a printable version to a file, make
1144some changes and then compare it with some other printed dictionary. In this
1145case, use the ``pprint`` module to pretty-print the dictionary; the items will
1146be presented in order sorted by the key.
1147
Georg Brandl62eaaf62009-12-19 17:51:41 +00001148A more complicated solution is to subclass ``dict`` to create a
Georg Brandld7413152009-10-11 21:25:26 +00001149``SortedDict`` class that prints itself in a predictable order. Here's one
1150simpleminded implementation of such a class::
1151
Georg Brandl62eaaf62009-12-19 17:51:41 +00001152 class SortedDict(dict):
Georg Brandld7413152009-10-11 21:25:26 +00001153 def __repr__(self):
Georg Brandl62eaaf62009-12-19 17:51:41 +00001154 keys = sorted(self.keys())
1155 result = ("{!r}: {!r}".format(k, self[k]) for k in keys)
1156 return "{{{}}}".format(", ".join(result))
Georg Brandld7413152009-10-11 21:25:26 +00001157
Georg Brandl62eaaf62009-12-19 17:51:41 +00001158 __str__ = __repr__
Georg Brandld7413152009-10-11 21:25:26 +00001159
1160This will work for many common situations you might encounter, though it's far
1161from a perfect solution. The largest flaw is that if some values in the
1162dictionary are also dictionaries, their values won't be presented in any
1163particular order.
1164
1165
1166I want to do a complicated sort: can you do a Schwartzian Transform in Python?
1167------------------------------------------------------------------------------
1168
1169The technique, attributed to Randal Schwartz of the Perl community, sorts the
1170elements of a list by a metric which maps each element to its "sort value". In
1171Python, just use the ``key`` argument for the ``sort()`` method::
1172
1173 Isorted = L[:]
1174 Isorted.sort(key=lambda s: int(s[10:15]))
1175
1176The ``key`` argument is new in Python 2.4, for older versions this kind of
1177sorting is quite simple to do with list comprehensions. To sort a list of
1178strings by their uppercase values::
1179
Georg Brandl62eaaf62009-12-19 17:51:41 +00001180 tmp1 = [(x.upper(), x) for x in L] # Schwartzian transform
Georg Brandld7413152009-10-11 21:25:26 +00001181 tmp1.sort()
1182 Usorted = [x[1] for x in tmp1]
1183
1184To sort by the integer value of a subfield extending from positions 10-15 in
1185each string::
1186
Georg Brandl62eaaf62009-12-19 17:51:41 +00001187 tmp2 = [(int(s[10:15]), s) for s in L] # Schwartzian transform
Georg Brandld7413152009-10-11 21:25:26 +00001188 tmp2.sort()
1189 Isorted = [x[1] for x in tmp2]
1190
Georg Brandl62eaaf62009-12-19 17:51:41 +00001191For versions prior to 3.0, Isorted may also be computed by ::
Georg Brandld7413152009-10-11 21:25:26 +00001192
1193 def intfield(s):
1194 return int(s[10:15])
1195
1196 def Icmp(s1, s2):
1197 return cmp(intfield(s1), intfield(s2))
1198
1199 Isorted = L[:]
1200 Isorted.sort(Icmp)
1201
1202but since this method calls ``intfield()`` many times for each element of L, it
1203is slower than the Schwartzian Transform.
1204
1205
1206How can I sort one list by values from another list?
1207----------------------------------------------------
1208
Georg Brandl62eaaf62009-12-19 17:51:41 +00001209Merge them into an iterator of tuples, sort the resulting list, and then pick
Georg Brandld7413152009-10-11 21:25:26 +00001210out the element you want. ::
1211
1212 >>> list1 = ["what", "I'm", "sorting", "by"]
1213 >>> list2 = ["something", "else", "to", "sort"]
1214 >>> pairs = zip(list1, list2)
Georg Brandl62eaaf62009-12-19 17:51:41 +00001215 >>> pairs = sorted(pairs)
Georg Brandld7413152009-10-11 21:25:26 +00001216 >>> pairs
Georg Brandl62eaaf62009-12-19 17:51:41 +00001217 [("I'm", 'else'), ('by', 'sort'), ('sorting', 'to'), ('what', 'something')]
1218 >>> result = [x[1] for x in pairs]
Georg Brandld7413152009-10-11 21:25:26 +00001219 >>> result
1220 ['else', 'sort', 'to', 'something']
1221
Georg Brandl62eaaf62009-12-19 17:51:41 +00001222
Georg Brandld7413152009-10-11 21:25:26 +00001223An alternative for the last step is::
1224
Georg Brandl62eaaf62009-12-19 17:51:41 +00001225 >>> result = []
1226 >>> for p in pairs: result.append(p[1])
Georg Brandld7413152009-10-11 21:25:26 +00001227
1228If you find this more legible, you might prefer to use this instead of the final
1229list comprehension. However, it is almost twice as slow for long lists. Why?
1230First, the ``append()`` operation has to reallocate memory, and while it uses
1231some tricks to avoid doing that each time, it still has to do it occasionally,
1232and that costs quite a bit. Second, the expression "result.append" requires an
1233extra attribute lookup, and third, there's a speed reduction from having to make
1234all those function calls.
1235
1236
1237Objects
1238=======
1239
1240What is a class?
1241----------------
1242
1243A class is the particular object type created by executing a class statement.
1244Class objects are used as templates to create instance objects, which embody
1245both the data (attributes) and code (methods) specific to a datatype.
1246
1247A class can be based on one or more other classes, called its base class(es). It
1248then inherits the attributes and methods of its base classes. This allows an
1249object model to be successively refined by inheritance. You might have a
1250generic ``Mailbox`` class that provides basic accessor methods for a mailbox,
1251and subclasses such as ``MboxMailbox``, ``MaildirMailbox``, ``OutlookMailbox``
1252that handle various specific mailbox formats.
1253
1254
1255What is a method?
1256-----------------
1257
1258A method is a function on some object ``x`` that you normally call as
1259``x.name(arguments...)``. Methods are defined as functions inside the class
1260definition::
1261
1262 class C:
1263 def meth (self, arg):
1264 return arg * 2 + self.attribute
1265
1266
1267What is self?
1268-------------
1269
1270Self is merely a conventional name for the first argument of a method. A method
1271defined as ``meth(self, a, b, c)`` should be called as ``x.meth(a, b, c)`` for
1272some instance ``x`` of the class in which the definition occurs; the called
1273method will think it is called as ``meth(x, a, b, c)``.
1274
1275See also :ref:`why-self`.
1276
1277
1278How do I check if an object is an instance of a given class or of a subclass of it?
1279-----------------------------------------------------------------------------------
1280
1281Use the built-in function ``isinstance(obj, cls)``. You can check if an object
1282is an instance of any of a number of classes by providing a tuple instead of a
1283single class, e.g. ``isinstance(obj, (class1, class2, ...))``, and can also
1284check whether an object is one of Python's built-in types, e.g.
Georg Brandl62eaaf62009-12-19 17:51:41 +00001285``isinstance(obj, str)`` or ``isinstance(obj, (int, float, complex))``.
Georg Brandld7413152009-10-11 21:25:26 +00001286
1287Note that most programs do not use :func:`isinstance` on user-defined classes
1288very often. If you are developing the classes yourself, a more proper
1289object-oriented style is to define methods on the classes that encapsulate a
1290particular behaviour, instead of checking the object's class and doing a
1291different thing based on what class it is. For example, if you have a function
1292that does something::
1293
Georg Brandl62eaaf62009-12-19 17:51:41 +00001294 def search(obj):
Georg Brandld7413152009-10-11 21:25:26 +00001295 if isinstance(obj, Mailbox):
1296 # ... code to search a mailbox
1297 elif isinstance(obj, Document):
1298 # ... code to search a document
1299 elif ...
1300
1301A better approach is to define a ``search()`` method on all the classes and just
1302call it::
1303
1304 class Mailbox:
1305 def search(self):
1306 # ... code to search a mailbox
1307
1308 class Document:
1309 def search(self):
1310 # ... code to search a document
1311
1312 obj.search()
1313
1314
1315What is delegation?
1316-------------------
1317
1318Delegation is an object oriented technique (also called a design pattern).
1319Let's say you have an object ``x`` and want to change the behaviour of just one
1320of its methods. You can create a new class that provides a new implementation
1321of the method you're interested in changing and delegates all other methods to
1322the corresponding method of ``x``.
1323
1324Python programmers can easily implement delegation. For example, the following
1325class implements a class that behaves like a file but converts all written data
1326to uppercase::
1327
1328 class UpperOut:
1329
1330 def __init__(self, outfile):
1331 self._outfile = outfile
1332
1333 def write(self, s):
1334 self._outfile.write(s.upper())
1335
1336 def __getattr__(self, name):
1337 return getattr(self._outfile, name)
1338
1339Here the ``UpperOut`` class redefines the ``write()`` method to convert the
1340argument string to uppercase before calling the underlying
1341``self.__outfile.write()`` method. All other methods are delegated to the
1342underlying ``self.__outfile`` object. The delegation is accomplished via the
1343``__getattr__`` method; consult :ref:`the language reference <attribute-access>`
1344for more information about controlling attribute access.
1345
1346Note that for more general cases delegation can get trickier. When attributes
1347must be set as well as retrieved, the class must define a :meth:`__setattr__`
1348method too, and it must do so carefully. The basic implementation of
1349:meth:`__setattr__` is roughly equivalent to the following::
1350
1351 class X:
1352 ...
1353 def __setattr__(self, name, value):
1354 self.__dict__[name] = value
1355 ...
1356
1357Most :meth:`__setattr__` implementations must modify ``self.__dict__`` to store
1358local state for self without causing an infinite recursion.
1359
1360
1361How do I call a method defined in a base class from a derived class that overrides it?
1362--------------------------------------------------------------------------------------
1363
Georg Brandl62eaaf62009-12-19 17:51:41 +00001364Use the built-in :func:`super` function::
Georg Brandld7413152009-10-11 21:25:26 +00001365
1366 class Derived(Base):
1367 def meth (self):
1368 super(Derived, self).meth()
1369
Georg Brandl62eaaf62009-12-19 17:51:41 +00001370For version prior to 3.0, you may be using classic classes: For a class
1371definition such as ``class Derived(Base): ...`` you can call method ``meth()``
1372defined in ``Base`` (or one of ``Base``'s base classes) as ``Base.meth(self,
1373arguments...)``. Here, ``Base.meth`` is an unbound method, so you need to
1374provide the ``self`` argument.
Georg Brandld7413152009-10-11 21:25:26 +00001375
1376
1377How can I organize my code to make it easier to change the base class?
1378----------------------------------------------------------------------
1379
1380You could define an alias for the base class, assign the real base class to it
1381before your class definition, and use the alias throughout your class. Then all
1382you have to change is the value assigned to the alias. Incidentally, this trick
1383is also handy if you want to decide dynamically (e.g. depending on availability
1384of resources) which base class to use. Example::
1385
1386 BaseAlias = <real base class>
1387
1388 class Derived(BaseAlias):
1389 def meth(self):
1390 BaseAlias.meth(self)
1391 ...
1392
1393
1394How do I create static class data and static class methods?
1395-----------------------------------------------------------
1396
Georg Brandl62eaaf62009-12-19 17:51:41 +00001397Both static data and static methods (in the sense of C++ or Java) are supported
1398in Python.
Georg Brandld7413152009-10-11 21:25:26 +00001399
1400For static data, simply define a class attribute. To assign a new value to the
1401attribute, you have to explicitly use the class name in the assignment::
1402
1403 class C:
1404 count = 0 # number of times C.__init__ called
1405
1406 def __init__(self):
1407 C.count = C.count + 1
1408
1409 def getcount(self):
1410 return C.count # or return self.count
1411
1412``c.count`` also refers to ``C.count`` for any ``c`` such that ``isinstance(c,
1413C)`` holds, unless overridden by ``c`` itself or by some class on the base-class
1414search path from ``c.__class__`` back to ``C``.
1415
1416Caution: within a method of C, an assignment like ``self.count = 42`` creates a
Georg Brandl62eaaf62009-12-19 17:51:41 +00001417new and unrelated instance named "count" in ``self``'s own dict. Rebinding of a
1418class-static data name must always specify the class whether inside a method or
1419not::
Georg Brandld7413152009-10-11 21:25:26 +00001420
1421 C.count = 314
1422
1423Static methods are possible since Python 2.2::
1424
1425 class C:
1426 def static(arg1, arg2, arg3):
1427 # No 'self' parameter!
1428 ...
1429 static = staticmethod(static)
1430
1431With Python 2.4's decorators, this can also be written as ::
1432
1433 class C:
1434 @staticmethod
1435 def static(arg1, arg2, arg3):
1436 # No 'self' parameter!
1437 ...
1438
1439However, a far more straightforward way to get the effect of a static method is
1440via a simple module-level function::
1441
1442 def getcount():
1443 return C.count
1444
1445If your code is structured so as to define one class (or tightly related class
1446hierarchy) per module, this supplies the desired encapsulation.
1447
1448
1449How can I overload constructors (or methods) in Python?
1450-------------------------------------------------------
1451
1452This answer actually applies to all methods, but the question usually comes up
1453first in the context of constructors.
1454
1455In C++ you'd write
1456
1457.. code-block:: c
1458
1459 class C {
1460 C() { cout << "No arguments\n"; }
1461 C(int i) { cout << "Argument is " << i << "\n"; }
1462 }
1463
1464In Python you have to write a single constructor that catches all cases using
1465default arguments. For example::
1466
1467 class C:
1468 def __init__(self, i=None):
1469 if i is None:
Georg Brandl62eaaf62009-12-19 17:51:41 +00001470 print("No arguments")
Georg Brandld7413152009-10-11 21:25:26 +00001471 else:
Georg Brandl62eaaf62009-12-19 17:51:41 +00001472 print("Argument is", i)
Georg Brandld7413152009-10-11 21:25:26 +00001473
1474This is not entirely equivalent, but close enough in practice.
1475
1476You could also try a variable-length argument list, e.g. ::
1477
1478 def __init__(self, *args):
1479 ...
1480
1481The same approach works for all method definitions.
1482
1483
1484I try to use __spam and I get an error about _SomeClassName__spam.
1485------------------------------------------------------------------
1486
1487Variable names with double leading underscores are "mangled" to provide a simple
1488but effective way to define class private variables. Any identifier of the form
1489``__spam`` (at least two leading underscores, at most one trailing underscore)
1490is textually replaced with ``_classname__spam``, where ``classname`` is the
1491current class name with any leading underscores stripped.
1492
1493This doesn't guarantee privacy: an outside user can still deliberately access
1494the "_classname__spam" attribute, and private values are visible in the object's
1495``__dict__``. Many Python programmers never bother to use private variable
1496names at all.
1497
1498
1499My class defines __del__ but it is not called when I delete the object.
1500-----------------------------------------------------------------------
1501
1502There are several possible reasons for this.
1503
1504The del statement does not necessarily call :meth:`__del__` -- it simply
1505decrements the object's reference count, and if this reaches zero
1506:meth:`__del__` is called.
1507
1508If your data structures contain circular links (e.g. a tree where each child has
1509a parent reference and each parent has a list of children) the reference counts
1510will never go back to zero. Once in a while Python runs an algorithm to detect
1511such cycles, but the garbage collector might run some time after the last
1512reference to your data structure vanishes, so your :meth:`__del__` method may be
1513called at an inconvenient and random time. This is inconvenient if you're trying
1514to reproduce a problem. Worse, the order in which object's :meth:`__del__`
1515methods are executed is arbitrary. You can run :func:`gc.collect` to force a
1516collection, but there *are* pathological cases where objects will never be
1517collected.
1518
1519Despite the cycle collector, it's still a good idea to define an explicit
1520``close()`` method on objects to be called whenever you're done with them. The
1521``close()`` method can then remove attributes that refer to subobjecs. Don't
1522call :meth:`__del__` directly -- :meth:`__del__` should call ``close()`` and
1523``close()`` should make sure that it can be called more than once for the same
1524object.
1525
1526Another way to avoid cyclical references is to use the :mod:`weakref` module,
1527which allows you to point to objects without incrementing their reference count.
1528Tree data structures, for instance, should use weak references for their parent
1529and sibling references (if they need them!).
1530
Georg Brandl62eaaf62009-12-19 17:51:41 +00001531.. XXX relevant for Python 3?
1532
1533 If the object has ever been a local variable in a function that caught an
1534 expression in an except clause, chances are that a reference to the object
1535 still exists in that function's stack frame as contained in the stack trace.
1536 Normally, calling :func:`sys.exc_clear` will take care of this by clearing
1537 the last recorded exception.
Georg Brandld7413152009-10-11 21:25:26 +00001538
1539Finally, if your :meth:`__del__` method raises an exception, a warning message
1540is printed to :data:`sys.stderr`.
1541
1542
1543How do I get a list of all instances of a given class?
1544------------------------------------------------------
1545
1546Python does not keep track of all instances of a class (or of a built-in type).
1547You can program the class's constructor to keep track of all instances by
1548keeping a list of weak references to each instance.
1549
1550
1551Modules
1552=======
1553
1554How do I create a .pyc file?
1555----------------------------
1556
1557When a module is imported for the first time (or when the source is more recent
1558than the current compiled file) a ``.pyc`` file containing the compiled code
1559should be created in the same directory as the ``.py`` file.
1560
1561One reason that a ``.pyc`` file may not be created is permissions problems with
1562the directory. This can happen, for example, if you develop as one user but run
1563as another, such as if you are testing with a web server. Creation of a .pyc
1564file is automatic if you're importing a module and Python has the ability
1565(permissions, free space, etc...) to write the compiled module back to the
1566directory.
1567
1568Running Python on a top level script is not considered an import and no ``.pyc``
1569will be created. For example, if you have a top-level module ``abc.py`` that
1570imports another module ``xyz.py``, when you run abc, ``xyz.pyc`` will be created
1571since xyz is imported, but no ``abc.pyc`` file will be created since ``abc.py``
1572isn't being imported.
1573
1574If you need to create abc.pyc -- that is, to create a .pyc file for a module
1575that is not imported -- you can, using the :mod:`py_compile` and
1576:mod:`compileall` modules.
1577
1578The :mod:`py_compile` module can manually compile any module. One way is to use
1579the ``compile()`` function in that module interactively::
1580
1581 >>> import py_compile
1582 >>> py_compile.compile('abc.py')
1583
1584This will write the ``.pyc`` to the same location as ``abc.py`` (or you can
1585override that with the optional parameter ``cfile``).
1586
1587You can also automatically compile all files in a directory or directories using
1588the :mod:`compileall` module. You can do it from the shell prompt by running
1589``compileall.py`` and providing the path of a directory containing Python files
1590to compile::
1591
1592 python -m compileall .
1593
1594
1595How do I find the current module name?
1596--------------------------------------
1597
1598A module can find out its own module name by looking at the predefined global
1599variable ``__name__``. If this has the value ``'__main__'``, the program is
1600running as a script. Many modules that are usually used by importing them also
1601provide a command-line interface or a self-test, and only execute this code
1602after checking ``__name__``::
1603
1604 def main():
Georg Brandl62eaaf62009-12-19 17:51:41 +00001605 print('Running test...')
Georg Brandld7413152009-10-11 21:25:26 +00001606 ...
1607
1608 if __name__ == '__main__':
1609 main()
1610
1611
1612How can I have modules that mutually import each other?
1613-------------------------------------------------------
1614
1615Suppose you have the following modules:
1616
1617foo.py::
1618
1619 from bar import bar_var
1620 foo_var = 1
1621
1622bar.py::
1623
1624 from foo import foo_var
1625 bar_var = 2
1626
1627The problem is that the interpreter will perform the following steps:
1628
1629* main imports foo
1630* Empty globals for foo are created
1631* foo is compiled and starts executing
1632* foo imports bar
1633* Empty globals for bar are created
1634* bar is compiled and starts executing
1635* bar imports foo (which is a no-op since there already is a module named foo)
1636* bar.foo_var = foo.foo_var
1637
1638The last step fails, because Python isn't done with interpreting ``foo`` yet and
1639the global symbol dictionary for ``foo`` is still empty.
1640
1641The same thing happens when you use ``import foo``, and then try to access
1642``foo.foo_var`` in global code.
1643
1644There are (at least) three possible workarounds for this problem.
1645
1646Guido van Rossum recommends avoiding all uses of ``from <module> import ...``,
1647and placing all code inside functions. Initializations of global variables and
1648class variables should use constants or built-in functions only. This means
1649everything from an imported module is referenced as ``<module>.<name>``.
1650
1651Jim Roskind suggests performing steps in the following order in each module:
1652
1653* exports (globals, functions, and classes that don't need imported base
1654 classes)
1655* ``import`` statements
1656* active code (including globals that are initialized from imported values).
1657
1658van Rossum doesn't like this approach much because the imports appear in a
1659strange place, but it does work.
1660
1661Matthias Urlichs recommends restructuring your code so that the recursive import
1662is not necessary in the first place.
1663
1664These solutions are not mutually exclusive.
1665
1666
1667__import__('x.y.z') returns <module 'x'>; how do I get z?
1668---------------------------------------------------------
1669
1670Try::
1671
1672 __import__('x.y.z').y.z
1673
1674For more realistic situations, you may have to do something like ::
1675
1676 m = __import__(s)
1677 for i in s.split(".")[1:]:
1678 m = getattr(m, i)
1679
1680See :mod:`importlib` for a convenience function called
1681:func:`~importlib.import_module`.
1682
1683
1684
1685When I edit an imported module and reimport it, the changes don't show up. Why does this happen?
1686-------------------------------------------------------------------------------------------------
1687
1688For reasons of efficiency as well as consistency, Python only reads the module
1689file on the first time a module is imported. If it didn't, in a program
1690consisting of many modules where each one imports the same basic module, the
1691basic module would be parsed and re-parsed many times. To force rereading of a
1692changed module, do this::
1693
Georg Brandl62eaaf62009-12-19 17:51:41 +00001694 import imp
Georg Brandld7413152009-10-11 21:25:26 +00001695 import modname
Georg Brandl62eaaf62009-12-19 17:51:41 +00001696 imp.reload(modname)
Georg Brandld7413152009-10-11 21:25:26 +00001697
1698Warning: this technique is not 100% fool-proof. In particular, modules
1699containing statements like ::
1700
1701 from modname import some_objects
1702
1703will continue to work with the old version of the imported objects. If the
1704module contains class definitions, existing class instances will *not* be
1705updated to use the new class definition. This can result in the following
1706paradoxical behaviour:
1707
Georg Brandl62eaaf62009-12-19 17:51:41 +00001708 >>> import imp
Georg Brandld7413152009-10-11 21:25:26 +00001709 >>> import cls
1710 >>> c = cls.C() # Create an instance of C
Georg Brandl62eaaf62009-12-19 17:51:41 +00001711 >>> imp.reload(cls)
1712 <module 'cls' from 'cls.py'>
Georg Brandld7413152009-10-11 21:25:26 +00001713 >>> isinstance(c, cls.C) # isinstance is false?!?
1714 False
1715
Georg Brandl62eaaf62009-12-19 17:51:41 +00001716The nature of the problem is made clear if you print out the "identity" of the
1717class objects:
Georg Brandld7413152009-10-11 21:25:26 +00001718
Georg Brandl62eaaf62009-12-19 17:51:41 +00001719 >>> hex(id(c.__class__))
1720 '0x7352a0'
1721 >>> hex(id(cls.C))
1722 '0x4198d0'