blob: aac8e8165280d2f00e719f2b4fa93fc31ecddbb5 [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
Georg Brandld7413152009-10-11 21:25:26 +0000118Core Language
119=============
120
R. David Murrayc04a6942009-11-14 22:21:32 +0000121Why am I getting an UnboundLocalError when the variable has a value?
122--------------------------------------------------------------------
Georg Brandld7413152009-10-11 21:25:26 +0000123
R. David Murrayc04a6942009-11-14 22:21:32 +0000124It can be a surprise to get the UnboundLocalError in previously working
125code when it is modified by adding an assignment statement somewhere in
126the body of a function.
Georg Brandld7413152009-10-11 21:25:26 +0000127
R. David Murrayc04a6942009-11-14 22:21:32 +0000128This code:
Georg Brandld7413152009-10-11 21:25:26 +0000129
R. David Murrayc04a6942009-11-14 22:21:32 +0000130 >>> x = 10
131 >>> def bar():
132 ... print(x)
133 >>> bar()
134 10
Georg Brandld7413152009-10-11 21:25:26 +0000135
R. David Murrayc04a6942009-11-14 22:21:32 +0000136works, but this code:
Georg Brandld7413152009-10-11 21:25:26 +0000137
R. David Murrayc04a6942009-11-14 22:21:32 +0000138 >>> x = 10
139 >>> def foo():
140 ... print(x)
141 ... x += 1
Georg Brandld7413152009-10-11 21:25:26 +0000142
R. David Murrayc04a6942009-11-14 22:21:32 +0000143results in an UnboundLocalError:
Georg Brandld7413152009-10-11 21:25:26 +0000144
R. David Murrayc04a6942009-11-14 22:21:32 +0000145 >>> foo()
146 Traceback (most recent call last):
147 ...
148 UnboundLocalError: local variable 'x' referenced before assignment
149
150This is because when you make an assignment to a variable in a scope, that
151variable becomes local to that scope and shadows any similarly named variable
152in the outer scope. Since the last statement in foo assigns a new value to
153``x``, the compiler recognizes it as a local variable. Consequently when the
R. David Murray18163c32009-11-14 22:27:22 +0000154earlier ``print(x)`` attempts to print the uninitialized local variable and
R. David Murrayc04a6942009-11-14 22:21:32 +0000155an error results.
156
157In the example above you can access the outer scope variable by declaring it
158global:
159
160 >>> x = 10
161 >>> def foobar():
162 ... global x
163 ... print(x)
164 ... x += 1
165 >>> foobar()
166 10
167
168This explicit declaration is required in order to remind you that (unlike the
169superficially analogous situation with class and instance variables) you are
170actually modifying the value of the variable in the outer scope:
171
172 >>> print(x)
173 11
174
175You can do a similar thing in a nested scope using the :keyword:`nonlocal`
176keyword:
177
178 >>> def foo():
179 ... x = 10
180 ... def bar():
181 ... nonlocal x
182 ... print(x)
183 ... x += 1
184 ... bar()
185 ... print(x)
186 >>> foo()
187 10
188 11
Georg Brandld7413152009-10-11 21:25:26 +0000189
190
191What are the rules for local and global variables in Python?
192------------------------------------------------------------
193
194In Python, variables that are only referenced inside a function are implicitly
195global. If a variable is assigned a new value anywhere within the function's
196body, it's assumed to be a local. If a variable is ever assigned a new value
197inside the function, the variable is implicitly local, and you need to
198explicitly declare it as 'global'.
199
200Though a bit surprising at first, a moment's consideration explains this. On
201one hand, requiring :keyword:`global` for assigned variables provides a bar
202against unintended side-effects. On the other hand, if ``global`` was required
203for all global references, you'd be using ``global`` all the time. You'd have
Georg Brandlc4a55fc2010-02-06 18:46:57 +0000204to declare as global every reference to a built-in function or to a component of
Georg Brandld7413152009-10-11 21:25:26 +0000205an imported module. This clutter would defeat the usefulness of the ``global``
206declaration for identifying side-effects.
207
208
209How do I share global variables across modules?
210------------------------------------------------
211
212The canonical way to share information across modules within a single program is
213to create a special module (often called config or cfg). Just import the config
214module in all modules of your application; the module then becomes available as
215a global name. Because there is only one instance of each module, any changes
216made to the module object get reflected everywhere. For example:
217
218config.py::
219
220 x = 0 # Default value of the 'x' configuration setting
221
222mod.py::
223
224 import config
225 config.x = 1
226
227main.py::
228
229 import config
230 import mod
Georg Brandl62eaaf62009-12-19 17:51:41 +0000231 print(config.x)
Georg Brandld7413152009-10-11 21:25:26 +0000232
233Note that using a module is also the basis for implementing the Singleton design
234pattern, for the same reason.
235
236
237What are the "best practices" for using import in a module?
238-----------------------------------------------------------
239
240In general, don't use ``from modulename import *``. Doing so clutters the
241importer's namespace. Some people avoid this idiom even with the few modules
242that were designed to be imported in this manner. Modules designed in this
Georg Brandld404fa62009-10-13 16:55:12 +0000243manner include :mod:`tkinter`, and :mod:`threading`.
Georg Brandld7413152009-10-11 21:25:26 +0000244
245Import modules at the top of a file. Doing so makes it clear what other modules
246your code requires and avoids questions of whether the module name is in scope.
247Using one import per line makes it easy to add and delete module imports, but
248using multiple imports per line uses less screen space.
249
250It's good practice if you import modules in the following order:
251
Georg Brandl62eaaf62009-12-19 17:51:41 +00002521. standard library modules -- e.g. ``sys``, ``os``, ``getopt``, ``re``
Georg Brandld7413152009-10-11 21:25:26 +00002532. third-party library modules (anything installed in Python's site-packages
254 directory) -- e.g. mx.DateTime, ZODB, PIL.Image, etc.
2553. locally-developed modules
256
257Never use relative package imports. If you're writing code that's in the
258``package.sub.m1`` module and want to import ``package.sub.m2``, do not just
Georg Brandl11b63622009-12-20 14:21:27 +0000259write ``from . import m2``, even though it's legal. Write ``from package.sub
260import m2`` instead. See :pep:`328` for details.
Georg Brandld7413152009-10-11 21:25:26 +0000261
262It is sometimes necessary to move imports to a function or class to avoid
263problems with circular imports. Gordon McMillan says:
264
265 Circular imports are fine where both modules use the "import <module>" form
266 of import. They fail when the 2nd module wants to grab a name out of the
267 first ("from module import name") and the import is at the top level. That's
268 because names in the 1st are not yet available, because the first module is
269 busy importing the 2nd.
270
271In this case, if the second module is only used in one function, then the import
272can easily be moved into that function. By the time the import is called, the
273first module will have finished initializing, and the second module can do its
274import.
275
276It may also be necessary to move imports out of the top level of code if some of
277the modules are platform-specific. In that case, it may not even be possible to
278import all of the modules at the top of the file. In this case, importing the
279correct modules in the corresponding platform-specific code is a good option.
280
281Only move imports into a local scope, such as inside a function definition, if
282it's necessary to solve a problem such as avoiding a circular import or are
283trying to reduce the initialization time of a module. This technique is
284especially helpful if many of the imports are unnecessary depending on how the
285program executes. You may also want to move imports into a function if the
286modules are only ever used in that function. Note that loading a module the
287first time may be expensive because of the one time initialization of the
288module, but loading a module multiple times is virtually free, costing only a
289couple of dictionary lookups. Even if the module name has gone out of scope,
290the module is probably available in :data:`sys.modules`.
291
292If only instances of a specific class use a module, then it is reasonable to
293import the module in the class's ``__init__`` method and then assign the module
294to an instance variable so that the module is always available (via that
295instance variable) during the life of the object. Note that to delay an import
296until the class is instantiated, the import must be inside a method. Putting
297the import inside the class but outside of any method still causes the import to
298occur when the module is initialized.
299
300
301How can I pass optional or keyword parameters from one function to another?
302---------------------------------------------------------------------------
303
304Collect the arguments using the ``*`` and ``**`` specifiers in the function's
305parameter list; this gives you the positional arguments as a tuple and the
306keyword arguments as a dictionary. You can then pass these arguments when
307calling another function by using ``*`` and ``**``::
308
309 def f(x, *args, **kwargs):
310 ...
311 kwargs['width'] = '14.3c'
312 ...
313 g(x, *args, **kwargs)
314
Georg Brandld7413152009-10-11 21:25:26 +0000315
Chris Jerdonekb4309942012-12-25 14:54:44 -0800316.. index::
317 single: argument; difference from parameter
318 single: parameter; difference from argument
319
Chris Jerdonekc2a7fd62012-11-28 02:29:33 -0800320.. _faq-argument-vs-parameter:
321
322What is the difference between arguments and parameters?
323--------------------------------------------------------
324
325:term:`Parameters <parameter>` are defined by the names that appear in a
326function definition, whereas :term:`arguments <argument>` are the values
327actually passed to a function when calling it. Parameters define what types of
328arguments a function can accept. For example, given the function definition::
329
330 def func(foo, bar=None, **kwargs):
331 pass
332
333*foo*, *bar* and *kwargs* are parameters of ``func``. However, when calling
334``func``, for example::
335
336 func(42, bar=314, extra=somevar)
337
338the values ``42``, ``314``, and ``somevar`` are arguments.
339
340
Georg Brandld7413152009-10-11 21:25:26 +0000341How do I write a function with output parameters (call by reference)?
342---------------------------------------------------------------------
343
344Remember that arguments are passed by assignment in Python. Since assignment
345just creates references to objects, there's no alias between an argument name in
346the caller and callee, and so no call-by-reference per se. You can achieve the
347desired effect in a number of ways.
348
3491) By returning a tuple of the results::
350
351 def func2(a, b):
352 a = 'new-value' # a and b are local names
353 b = b + 1 # assigned to new objects
354 return a, b # return new values
355
356 x, y = 'old-value', 99
357 x, y = func2(x, y)
Georg Brandl62eaaf62009-12-19 17:51:41 +0000358 print(x, y) # output: new-value 100
Georg Brandld7413152009-10-11 21:25:26 +0000359
360 This is almost always the clearest solution.
361
3622) By using global variables. This isn't thread-safe, and is not recommended.
363
3643) By passing a mutable (changeable in-place) object::
365
366 def func1(a):
367 a[0] = 'new-value' # 'a' references a mutable list
368 a[1] = a[1] + 1 # changes a shared object
369
370 args = ['old-value', 99]
371 func1(args)
Georg Brandl62eaaf62009-12-19 17:51:41 +0000372 print(args[0], args[1]) # output: new-value 100
Georg Brandld7413152009-10-11 21:25:26 +0000373
3744) By passing in a dictionary that gets mutated::
375
376 def func3(args):
377 args['a'] = 'new-value' # args is a mutable dictionary
378 args['b'] = args['b'] + 1 # change it in-place
379
380 args = {'a':' old-value', 'b': 99}
381 func3(args)
Georg Brandl62eaaf62009-12-19 17:51:41 +0000382 print(args['a'], args['b'])
Georg Brandld7413152009-10-11 21:25:26 +0000383
3845) Or bundle up values in a class instance::
385
386 class callByRef:
387 def __init__(self, **args):
388 for (key, value) in args.items():
389 setattr(self, key, value)
390
391 def func4(args):
392 args.a = 'new-value' # args is a mutable callByRef
393 args.b = args.b + 1 # change object in-place
394
395 args = callByRef(a='old-value', b=99)
396 func4(args)
Georg Brandl62eaaf62009-12-19 17:51:41 +0000397 print(args.a, args.b)
Georg Brandld7413152009-10-11 21:25:26 +0000398
399
400 There's almost never a good reason to get this complicated.
401
402Your best choice is to return a tuple containing the multiple results.
403
404
405How do you make a higher order function in Python?
406--------------------------------------------------
407
408You have two choices: you can use nested scopes or you can use callable objects.
409For example, suppose you wanted to define ``linear(a,b)`` which returns a
410function ``f(x)`` that computes the value ``a*x+b``. Using nested scopes::
411
412 def linear(a, b):
413 def result(x):
414 return a * x + b
415 return result
416
417Or using a callable object::
418
419 class linear:
420
421 def __init__(self, a, b):
422 self.a, self.b = a, b
423
424 def __call__(self, x):
425 return self.a * x + self.b
426
427In both cases, ::
428
429 taxes = linear(0.3, 2)
430
431gives a callable object where ``taxes(10e6) == 0.3 * 10e6 + 2``.
432
433The callable object approach has the disadvantage that it is a bit slower and
434results in slightly longer code. However, note that a collection of callables
435can share their signature via inheritance::
436
437 class exponential(linear):
438 # __init__ inherited
439 def __call__(self, x):
440 return self.a * (x ** self.b)
441
442Object can encapsulate state for several methods::
443
444 class counter:
445
446 value = 0
447
448 def set(self, x):
449 self.value = x
450
451 def up(self):
452 self.value = self.value + 1
453
454 def down(self):
455 self.value = self.value - 1
456
457 count = counter()
458 inc, dec, reset = count.up, count.down, count.set
459
460Here ``inc()``, ``dec()`` and ``reset()`` act like functions which share the
461same counting variable.
462
463
464How do I copy an object in Python?
465----------------------------------
466
467In general, try :func:`copy.copy` or :func:`copy.deepcopy` for the general case.
468Not all objects can be copied, but most can.
469
470Some objects can be copied more easily. Dictionaries have a :meth:`~dict.copy`
471method::
472
473 newdict = olddict.copy()
474
475Sequences can be copied by slicing::
476
477 new_l = l[:]
478
479
480How can I find the methods or attributes of an object?
481------------------------------------------------------
482
483For an instance x of a user-defined class, ``dir(x)`` returns an alphabetized
484list of the names containing the instance attributes and methods and attributes
485defined by its class.
486
487
488How can my code discover the name of an object?
489-----------------------------------------------
490
491Generally speaking, it can't, because objects don't really have names.
492Essentially, assignment always binds a name to a value; The same is true of
493``def`` and ``class`` statements, but in that case the value is a
494callable. Consider the following code::
495
496 class A:
497 pass
498
499 B = A
500
501 a = B()
502 b = a
Georg Brandl62eaaf62009-12-19 17:51:41 +0000503 print(b)
504 <__main__.A object at 0x16D07CC>
505 print(a)
506 <__main__.A object at 0x16D07CC>
Georg Brandld7413152009-10-11 21:25:26 +0000507
508Arguably the class has a name: even though it is bound to two names and invoked
509through the name B the created instance is still reported as an instance of
510class A. However, it is impossible to say whether the instance's name is a or
511b, since both names are bound to the same value.
512
513Generally speaking it should not be necessary for your code to "know the names"
514of particular values. Unless you are deliberately writing introspective
515programs, this is usually an indication that a change of approach might be
516beneficial.
517
518In comp.lang.python, Fredrik Lundh once gave an excellent analogy in answer to
519this question:
520
521 The same way as you get the name of that cat you found on your porch: the cat
522 (object) itself cannot tell you its name, and it doesn't really care -- so
523 the only way to find out what it's called is to ask all your neighbours
524 (namespaces) if it's their cat (object)...
525
526 ....and don't be surprised if you'll find that it's known by many names, or
527 no name at all!
528
529
530What's up with the comma operator's precedence?
531-----------------------------------------------
532
533Comma is not an operator in Python. Consider this session::
534
535 >>> "a" in "b", "a"
Georg Brandl62eaaf62009-12-19 17:51:41 +0000536 (False, 'a')
Georg Brandld7413152009-10-11 21:25:26 +0000537
538Since the comma is not an operator, but a separator between expressions the
539above is evaluated as if you had entered::
540
541 >>> ("a" in "b"), "a"
542
543not::
544
Georg Brandl62eaaf62009-12-19 17:51:41 +0000545 >>> "a" in ("b", "a")
Georg Brandld7413152009-10-11 21:25:26 +0000546
547The same is true of the various assignment operators (``=``, ``+=`` etc). They
548are not truly operators but syntactic delimiters in assignment statements.
549
550
551Is there an equivalent of C's "?:" ternary operator?
552----------------------------------------------------
553
Antoine Pitrouc5b266e2011-12-03 22:11:11 +0100554Yes, there is. The syntax is as follows::
Georg Brandld7413152009-10-11 21:25:26 +0000555
556 [on_true] if [expression] else [on_false]
557
558 x, y = 50, 25
Georg Brandld7413152009-10-11 21:25:26 +0000559 small = x if x < y else y
560
Antoine Pitrouc5b266e2011-12-03 22:11:11 +0100561Before this syntax was introduced in Python 2.5, a common idiom was to use
562logical operators::
Georg Brandld7413152009-10-11 21:25:26 +0000563
Antoine Pitrouc5b266e2011-12-03 22:11:11 +0100564 [expression] and [on_true] or [on_false]
Georg Brandld7413152009-10-11 21:25:26 +0000565
Antoine Pitrouc5b266e2011-12-03 22:11:11 +0100566However, this idiom is unsafe, as it can give wrong results when *on_true*
567has a false boolean value. Therefore, it is always better to use
568the ``... if ... else ...`` form.
Georg Brandld7413152009-10-11 21:25:26 +0000569
570
571Is it possible to write obfuscated one-liners in Python?
572--------------------------------------------------------
573
574Yes. Usually this is done by nesting :keyword:`lambda` within
575:keyword:`lambda`. See the following three examples, due to Ulf Bartelt::
576
Georg Brandl62eaaf62009-12-19 17:51:41 +0000577 from functools import reduce
578
Georg Brandld7413152009-10-11 21:25:26 +0000579 # Primes < 1000
Georg Brandl62eaaf62009-12-19 17:51:41 +0000580 print(list(filter(None,map(lambda y:y*reduce(lambda x,y:x*y!=0,
581 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 +0000582
583 # First 10 Fibonacci numbers
Georg Brandl62eaaf62009-12-19 17:51:41 +0000584 print(list(map(lambda x,f=lambda x,f:(f(x-1,f)+f(x-2,f)) if x>1 else 1:
585 f(x,f), range(10))))
Georg Brandld7413152009-10-11 21:25:26 +0000586
587 # Mandelbrot set
Georg Brandl62eaaf62009-12-19 17:51:41 +0000588 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 +0000589 Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,Sy=Sy,L=lambda yc,Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,i=IM,
590 Sx=Sx,Sy=Sy:reduce(lambda x,y:x+y,map(lambda x,xc=Ru,yc=yc,Ru=Ru,Ro=Ro,
591 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
592 >=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(
593 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 +0000594 ))))(-2.1, 0.7, -1.2, 1.2, 30, 80, 24))
Georg Brandld7413152009-10-11 21:25:26 +0000595 # \___ ___/ \___ ___/ | | |__ lines on screen
596 # V V | |______ columns on screen
597 # | | |__________ maximum of "iterations"
598 # | |_________________ range on y axis
599 # |____________________________ range on x axis
600
601Don't try this at home, kids!
602
603
604Numbers and strings
605===================
606
607How do I specify hexadecimal and octal integers?
608------------------------------------------------
609
Georg Brandl62eaaf62009-12-19 17:51:41 +0000610To specify an octal digit, precede the octal value with a zero, and then a lower
611or uppercase "o". For example, to set the variable "a" to the octal value "10"
612(8 in decimal), type::
Georg Brandld7413152009-10-11 21:25:26 +0000613
Georg Brandl62eaaf62009-12-19 17:51:41 +0000614 >>> a = 0o10
Georg Brandld7413152009-10-11 21:25:26 +0000615 >>> a
616 8
617
618Hexadecimal is just as easy. Simply precede the hexadecimal number with a zero,
619and then a lower or uppercase "x". Hexadecimal digits can be specified in lower
620or uppercase. For example, in the Python interpreter::
621
622 >>> a = 0xa5
623 >>> a
624 165
625 >>> b = 0XB2
626 >>> b
627 178
628
629
Georg Brandl62eaaf62009-12-19 17:51:41 +0000630Why does -22 // 10 return -3?
631-----------------------------
Georg Brandld7413152009-10-11 21:25:26 +0000632
633It's primarily driven by the desire that ``i % j`` have the same sign as ``j``.
634If you want that, and also want::
635
Georg Brandl62eaaf62009-12-19 17:51:41 +0000636 i == (i // j) * j + (i % j)
Georg Brandld7413152009-10-11 21:25:26 +0000637
638then integer division has to return the floor. C also requires that identity to
Georg Brandl62eaaf62009-12-19 17:51:41 +0000639hold, and then compilers that truncate ``i // j`` need to make ``i % j`` have
640the same sign as ``i``.
Georg Brandld7413152009-10-11 21:25:26 +0000641
642There are few real use cases for ``i % j`` when ``j`` is negative. When ``j``
643is positive, there are many, and in virtually all of them it's more useful for
644``i % j`` to be ``>= 0``. If the clock says 10 now, what did it say 200 hours
645ago? ``-190 % 12 == 2`` is useful; ``-190 % 12 == -10`` is a bug waiting to
646bite.
647
648
649How do I convert a string to a number?
650--------------------------------------
651
652For integers, use the built-in :func:`int` type constructor, e.g. ``int('144')
653== 144``. Similarly, :func:`float` converts to floating-point,
654e.g. ``float('144') == 144.0``.
655
656By default, these interpret the number as decimal, so that ``int('0144') ==
657144`` and ``int('0x144')`` raises :exc:`ValueError`. ``int(string, base)`` takes
658the base to convert from as a second optional argument, so ``int('0x144', 16) ==
659324``. If the base is specified as 0, the number is interpreted using Python's
660rules: a leading '0' indicates octal, and '0x' indicates a hex number.
661
662Do not use the built-in function :func:`eval` if all you need is to convert
663strings to numbers. :func:`eval` will be significantly slower and it presents a
664security risk: someone could pass you a Python expression that might have
665unwanted side effects. For example, someone could pass
666``__import__('os').system("rm -rf $HOME")`` which would erase your home
667directory.
668
669:func:`eval` also has the effect of interpreting numbers as Python expressions,
Georg Brandl62eaaf62009-12-19 17:51:41 +0000670so that e.g. ``eval('09')`` gives a syntax error because Python does not allow
671leading '0' in a decimal number (except '0').
Georg Brandld7413152009-10-11 21:25:26 +0000672
673
674How do I convert a number to a string?
675--------------------------------------
676
677To convert, e.g., the number 144 to the string '144', use the built-in type
678constructor :func:`str`. If you want a hexadecimal or octal representation, use
Georg Brandl62eaaf62009-12-19 17:51:41 +0000679the built-in functions :func:`hex` or :func:`oct`. For fancy formatting, see
680the :ref:`string-formatting` section, e.g. ``"{:04d}".format(144)`` yields
Georg Brandl11b63622009-12-20 14:21:27 +0000681``'0144'`` and ``"{:.3f}".format(1/3)`` yields ``'0.333'``.
Georg Brandld7413152009-10-11 21:25:26 +0000682
683
684How do I modify a string in place?
685----------------------------------
686
Antoine Pitrouc5b266e2011-12-03 22:11:11 +0100687You can't, because strings are immutable. In most situations, you should
688simply construct a new string from the various parts you want to assemble
689it from. However, if you need an object with the ability to modify in-place
690unicode data, try using a :class:`io.StringIO` object or the :mod:`array`
691module::
Georg Brandld7413152009-10-11 21:25:26 +0000692
693 >>> s = "Hello, world"
Antoine Pitrouc5b266e2011-12-03 22:11:11 +0100694 >>> sio = io.StringIO(s)
695 >>> sio.getvalue()
696 'Hello, world'
697 >>> sio.seek(7)
698 7
699 >>> sio.write("there!")
700 6
701 >>> sio.getvalue()
Georg Brandld7413152009-10-11 21:25:26 +0000702 'Hello, there!'
703
704 >>> import array
Georg Brandl62eaaf62009-12-19 17:51:41 +0000705 >>> a = array.array('u', s)
706 >>> print(a)
707 array('u', 'Hello, world')
708 >>> a[0] = 'y'
709 >>> print(a)
710 array('u', 'yello world')
711 >>> a.tounicode()
Georg Brandld7413152009-10-11 21:25:26 +0000712 'yello, world'
713
714
715How do I use strings to call functions/methods?
716-----------------------------------------------
717
718There are various techniques.
719
720* The best is to use a dictionary that maps strings to functions. The primary
721 advantage of this technique is that the strings do not need to match the names
722 of the functions. This is also the primary technique used to emulate a case
723 construct::
724
725 def a():
726 pass
727
728 def b():
729 pass
730
731 dispatch = {'go': a, 'stop': b} # Note lack of parens for funcs
732
733 dispatch[get_input()]() # Note trailing parens to call function
734
735* Use the built-in function :func:`getattr`::
736
737 import foo
738 getattr(foo, 'bar')()
739
740 Note that :func:`getattr` works on any object, including classes, class
741 instances, modules, and so on.
742
743 This is used in several places in the standard library, like this::
744
745 class Foo:
746 def do_foo(self):
747 ...
748
749 def do_bar(self):
750 ...
751
752 f = getattr(foo_instance, 'do_' + opname)
753 f()
754
755
756* Use :func:`locals` or :func:`eval` to resolve the function name::
757
758 def myFunc():
Georg Brandl62eaaf62009-12-19 17:51:41 +0000759 print("hello")
Georg Brandld7413152009-10-11 21:25:26 +0000760
761 fname = "myFunc"
762
763 f = locals()[fname]
764 f()
765
766 f = eval(fname)
767 f()
768
769 Note: Using :func:`eval` is slow and dangerous. If you don't have absolute
770 control over the contents of the string, someone could pass a string that
771 resulted in an arbitrary function being executed.
772
773Is there an equivalent to Perl's chomp() for removing trailing newlines from strings?
774-------------------------------------------------------------------------------------
775
Antoine Pitrouf3520402011-12-03 22:19:55 +0100776You can use ``S.rstrip("\r\n")`` to remove all occurrences of any line
777terminator from the end of the string ``S`` without removing other trailing
778whitespace. If the string ``S`` represents more than one line, with several
779empty lines at the end, the line terminators for all the blank lines will
780be removed::
Georg Brandld7413152009-10-11 21:25:26 +0000781
782 >>> lines = ("line 1 \r\n"
783 ... "\r\n"
784 ... "\r\n")
785 >>> lines.rstrip("\n\r")
Georg Brandl62eaaf62009-12-19 17:51:41 +0000786 'line 1 '
Georg Brandld7413152009-10-11 21:25:26 +0000787
788Since this is typically only desired when reading text one line at a time, using
789``S.rstrip()`` this way works well.
790
Georg Brandld7413152009-10-11 21:25:26 +0000791
792Is there a scanf() or sscanf() equivalent?
793------------------------------------------
794
795Not as such.
796
797For simple input parsing, the easiest approach is usually to split the line into
798whitespace-delimited words using the :meth:`~str.split` method of string objects
799and then convert decimal strings to numeric values using :func:`int` or
800:func:`float`. ``split()`` supports an optional "sep" parameter which is useful
801if the line uses something other than whitespace as a separator.
802
Brian Curtin5a7a52f2010-09-23 13:45:21 +0000803For more complicated input parsing, regular expressions are more powerful
Georg Brandl60203b42010-10-06 10:11:56 +0000804than C's :c:func:`sscanf` and better suited for the task.
Georg Brandld7413152009-10-11 21:25:26 +0000805
806
Georg Brandl62eaaf62009-12-19 17:51:41 +0000807What does 'UnicodeDecodeError' or 'UnicodeEncodeError' error mean?
808-------------------------------------------------------------------
Georg Brandld7413152009-10-11 21:25:26 +0000809
Georg Brandl62eaaf62009-12-19 17:51:41 +0000810See the :ref:`unicode-howto`.
Georg Brandld7413152009-10-11 21:25:26 +0000811
812
Antoine Pitrou432259f2011-12-09 23:10:31 +0100813Performance
814===========
815
816My program is too slow. How do I speed it up?
817---------------------------------------------
818
819That's a tough one, in general. First, here are a list of things to
820remember before diving further:
821
Georg Brandl300a6912012-03-14 22:40:08 +0100822* Performance characteristics vary across Python implementations. This FAQ
Antoine Pitrou432259f2011-12-09 23:10:31 +0100823 focusses on :term:`CPython`.
Georg Brandl300a6912012-03-14 22:40:08 +0100824* Behaviour can vary across operating systems, especially when talking about
Antoine Pitrou432259f2011-12-09 23:10:31 +0100825 I/O or multi-threading.
826* You should always find the hot spots in your program *before* attempting to
827 optimize any code (see the :mod:`profile` module).
828* Writing benchmark scripts will allow you to iterate quickly when searching
829 for improvements (see the :mod:`timeit` module).
830* It is highly recommended to have good code coverage (through unit testing
831 or any other technique) before potentially introducing regressions hidden
832 in sophisticated optimizations.
833
834That being said, there are many tricks to speed up Python code. Here are
835some general principles which go a long way towards reaching acceptable
836performance levels:
837
838* Making your algorithms faster (or changing to faster ones) can yield
839 much larger benefits than trying to sprinkle micro-optimization tricks
840 all over your code.
841
842* Use the right data structures. Study documentation for the :ref:`bltin-types`
843 and the :mod:`collections` module.
844
845* When the standard library provides a primitive for doing something, it is
846 likely (although not guaranteed) to be faster than any alternative you
847 may come up with. This is doubly true for primitives written in C, such
848 as builtins and some extension types. For example, be sure to use
849 either the :meth:`list.sort` built-in method or the related :func:`sorted`
850 function to do sorting (and see the
851 `sorting mini-HOWTO <http://wiki.python.org/moin/HowTo/Sorting>`_ for examples
852 of moderately advanced usage).
853
854* Abstractions tend to create indirections and force the interpreter to work
855 more. If the levels of indirection outweigh the amount of useful work
856 done, your program will be slower. You should avoid excessive abstraction,
857 especially under the form of tiny functions or methods (which are also often
858 detrimental to readability).
859
860If you have reached the limit of what pure Python can allow, there are tools
861to take you further away. For example, `Cython <http://cython.org>`_ can
862compile a slightly modified version of Python code into a C extension, and
863can be used on many different platforms. Cython can take advantage of
864compilation (and optional type annotations) to make your code significantly
865faster than when interpreted. If you are confident in your C programming
866skills, you can also :ref:`write a C extension module <extending-index>`
867yourself.
868
869.. seealso::
870 The wiki page devoted to `performance tips
871 <http://wiki.python.org/moin/PythonSpeed/PerformanceTips>`_.
872
873.. _efficient_string_concatenation:
874
Antoine Pitroufd9ebd42011-11-25 16:33:53 +0100875What is the most efficient way to concatenate many strings together?
876--------------------------------------------------------------------
877
878:class:`str` and :class:`bytes` objects are immutable, therefore concatenating
879many strings together is inefficient as each concatenation creates a new
880object. In the general case, the total runtime cost is quadratic in the
881total string length.
882
883To accumulate many :class:`str` objects, the recommended idiom is to place
884them into a list and call :meth:`str.join` at the end::
885
886 chunks = []
887 for s in my_strings:
888 chunks.append(s)
889 result = ''.join(chunks)
890
891(another reasonably efficient idiom is to use :class:`io.StringIO`)
892
893To accumulate many :class:`bytes` objects, the recommended idiom is to extend
894a :class:`bytearray` object using in-place concatenation (the ``+=`` operator)::
895
896 result = bytearray()
897 for b in my_bytes_objects:
898 result += b
899
900
Georg Brandld7413152009-10-11 21:25:26 +0000901Sequences (Tuples/Lists)
902========================
903
904How do I convert between tuples and lists?
905------------------------------------------
906
907The type constructor ``tuple(seq)`` converts any sequence (actually, any
908iterable) into a tuple with the same items in the same order.
909
910For example, ``tuple([1, 2, 3])`` yields ``(1, 2, 3)`` and ``tuple('abc')``
911yields ``('a', 'b', 'c')``. If the argument is a tuple, it does not make a copy
912but returns the same object, so it is cheap to call :func:`tuple` when you
913aren't sure that an object is already a tuple.
914
915The type constructor ``list(seq)`` converts any sequence or iterable into a list
916with the same items in the same order. For example, ``list((1, 2, 3))`` yields
917``[1, 2, 3]`` and ``list('abc')`` yields ``['a', 'b', 'c']``. If the argument
918is a list, it makes a copy just like ``seq[:]`` would.
919
920
921What's a negative index?
922------------------------
923
924Python sequences are indexed with positive numbers and negative numbers. For
925positive numbers 0 is the first index 1 is the second index and so forth. For
926negative indices -1 is the last index and -2 is the penultimate (next to last)
927index and so forth. Think of ``seq[-n]`` as the same as ``seq[len(seq)-n]``.
928
929Using negative indices can be very convenient. For example ``S[:-1]`` is all of
930the string except for its last character, which is useful for removing the
931trailing newline from a string.
932
933
934How do I iterate over a sequence in reverse order?
935--------------------------------------------------
936
Georg Brandlc4a55fc2010-02-06 18:46:57 +0000937Use the :func:`reversed` built-in function, which is new in Python 2.4::
Georg Brandld7413152009-10-11 21:25:26 +0000938
939 for x in reversed(sequence):
940 ... # do something with x...
941
942This won't touch your original sequence, but build a new copy with reversed
943order to iterate over.
944
945With Python 2.3, you can use an extended slice syntax::
946
947 for x in sequence[::-1]:
948 ... # do something with x...
949
950
951How do you remove duplicates from a list?
952-----------------------------------------
953
954See the Python Cookbook for a long discussion of many ways to do this:
955
956 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52560
957
958If you don't mind reordering the list, sort it and then scan from the end of the
959list, deleting duplicates as you go::
960
Georg Brandl62eaaf62009-12-19 17:51:41 +0000961 if mylist:
962 mylist.sort()
963 last = mylist[-1]
964 for i in range(len(mylist)-2, -1, -1):
965 if last == mylist[i]:
966 del mylist[i]
Georg Brandld7413152009-10-11 21:25:26 +0000967 else:
Georg Brandl62eaaf62009-12-19 17:51:41 +0000968 last = mylist[i]
Georg Brandld7413152009-10-11 21:25:26 +0000969
Antoine Pitrouf3520402011-12-03 22:19:55 +0100970If all elements of the list may be used as set keys (i.e. they are all
971:term:`hashable`) this is often faster ::
Georg Brandld7413152009-10-11 21:25:26 +0000972
Georg Brandl62eaaf62009-12-19 17:51:41 +0000973 mylist = list(set(mylist))
Georg Brandld7413152009-10-11 21:25:26 +0000974
975This converts the list into a set, thereby removing duplicates, and then back
976into a list.
977
978
979How do you make an array in Python?
980-----------------------------------
981
982Use a list::
983
984 ["this", 1, "is", "an", "array"]
985
986Lists are equivalent to C or Pascal arrays in their time complexity; the primary
987difference is that a Python list can contain objects of many different types.
988
989The ``array`` module also provides methods for creating arrays of fixed types
990with compact representations, but they are slower to index than lists. Also
991note that the Numeric extensions and others define array-like structures with
992various characteristics as well.
993
994To get Lisp-style linked lists, you can emulate cons cells using tuples::
995
996 lisp_list = ("like", ("this", ("example", None) ) )
997
998If mutability is desired, you could use lists instead of tuples. Here the
999analogue of lisp car is ``lisp_list[0]`` and the analogue of cdr is
1000``lisp_list[1]``. Only do this if you're sure you really need to, because it's
1001usually a lot slower than using Python lists.
1002
1003
1004How do I create a multidimensional list?
1005----------------------------------------
1006
1007You probably tried to make a multidimensional array like this::
1008
1009 A = [[None] * 2] * 3
1010
1011This looks correct if you print it::
1012
1013 >>> A
1014 [[None, None], [None, None], [None, None]]
1015
1016But when you assign a value, it shows up in multiple places:
1017
1018 >>> A[0][0] = 5
1019 >>> A
1020 [[5, None], [5, None], [5, None]]
1021
1022The reason is that replicating a list with ``*`` doesn't create copies, it only
1023creates references to the existing objects. The ``*3`` creates a list
1024containing 3 references to the same list of length two. Changes to one row will
1025show in all rows, which is almost certainly not what you want.
1026
1027The suggested approach is to create a list of the desired length first and then
1028fill in each element with a newly created list::
1029
1030 A = [None] * 3
1031 for i in range(3):
1032 A[i] = [None] * 2
1033
1034This generates a list containing 3 different lists of length two. You can also
1035use a list comprehension::
1036
1037 w, h = 2, 3
1038 A = [[None] * w for i in range(h)]
1039
1040Or, you can use an extension that provides a matrix datatype; `Numeric Python
Georg Brandl495f7b52009-10-27 15:28:25 +00001041<http://numpy.scipy.org/>`_ is the best known.
Georg Brandld7413152009-10-11 21:25:26 +00001042
1043
1044How do I apply a method to a sequence of objects?
1045-------------------------------------------------
1046
1047Use a list comprehension::
1048
Georg Brandl62eaaf62009-12-19 17:51:41 +00001049 result = [obj.method() for obj in mylist]
Georg Brandld7413152009-10-11 21:25:26 +00001050
1051
1052Dictionaries
1053============
1054
1055How can I get a dictionary to display its keys in a consistent order?
1056---------------------------------------------------------------------
1057
1058You can't. Dictionaries store their keys in an unpredictable order, so the
1059display order of a dictionary's elements will be similarly unpredictable.
1060
1061This can be frustrating if you want to save a printable version to a file, make
1062some changes and then compare it with some other printed dictionary. In this
1063case, use the ``pprint`` module to pretty-print the dictionary; the items will
1064be presented in order sorted by the key.
1065
Georg Brandl62eaaf62009-12-19 17:51:41 +00001066A more complicated solution is to subclass ``dict`` to create a
Georg Brandld7413152009-10-11 21:25:26 +00001067``SortedDict`` class that prints itself in a predictable order. Here's one
1068simpleminded implementation of such a class::
1069
Georg Brandl62eaaf62009-12-19 17:51:41 +00001070 class SortedDict(dict):
Georg Brandld7413152009-10-11 21:25:26 +00001071 def __repr__(self):
Georg Brandl62eaaf62009-12-19 17:51:41 +00001072 keys = sorted(self.keys())
1073 result = ("{!r}: {!r}".format(k, self[k]) for k in keys)
1074 return "{{{}}}".format(", ".join(result))
Georg Brandld7413152009-10-11 21:25:26 +00001075
Georg Brandl62eaaf62009-12-19 17:51:41 +00001076 __str__ = __repr__
Georg Brandld7413152009-10-11 21:25:26 +00001077
1078This will work for many common situations you might encounter, though it's far
1079from a perfect solution. The largest flaw is that if some values in the
1080dictionary are also dictionaries, their values won't be presented in any
1081particular order.
1082
1083
1084I want to do a complicated sort: can you do a Schwartzian Transform in Python?
1085------------------------------------------------------------------------------
1086
1087The technique, attributed to Randal Schwartz of the Perl community, sorts the
1088elements of a list by a metric which maps each element to its "sort value". In
1089Python, just use the ``key`` argument for the ``sort()`` method::
1090
1091 Isorted = L[:]
1092 Isorted.sort(key=lambda s: int(s[10:15]))
1093
1094The ``key`` argument is new in Python 2.4, for older versions this kind of
1095sorting is quite simple to do with list comprehensions. To sort a list of
1096strings by their uppercase values::
1097
Georg Brandl62eaaf62009-12-19 17:51:41 +00001098 tmp1 = [(x.upper(), x) for x in L] # Schwartzian transform
Georg Brandld7413152009-10-11 21:25:26 +00001099 tmp1.sort()
1100 Usorted = [x[1] for x in tmp1]
1101
1102To sort by the integer value of a subfield extending from positions 10-15 in
1103each string::
1104
Georg Brandl62eaaf62009-12-19 17:51:41 +00001105 tmp2 = [(int(s[10:15]), s) for s in L] # Schwartzian transform
Georg Brandld7413152009-10-11 21:25:26 +00001106 tmp2.sort()
1107 Isorted = [x[1] for x in tmp2]
1108
Georg Brandl62eaaf62009-12-19 17:51:41 +00001109For versions prior to 3.0, Isorted may also be computed by ::
Georg Brandld7413152009-10-11 21:25:26 +00001110
1111 def intfield(s):
1112 return int(s[10:15])
1113
1114 def Icmp(s1, s2):
1115 return cmp(intfield(s1), intfield(s2))
1116
1117 Isorted = L[:]
1118 Isorted.sort(Icmp)
1119
1120but since this method calls ``intfield()`` many times for each element of L, it
1121is slower than the Schwartzian Transform.
1122
1123
1124How can I sort one list by values from another list?
1125----------------------------------------------------
1126
Georg Brandl62eaaf62009-12-19 17:51:41 +00001127Merge them into an iterator of tuples, sort the resulting list, and then pick
Georg Brandld7413152009-10-11 21:25:26 +00001128out the element you want. ::
1129
1130 >>> list1 = ["what", "I'm", "sorting", "by"]
1131 >>> list2 = ["something", "else", "to", "sort"]
1132 >>> pairs = zip(list1, list2)
Georg Brandl62eaaf62009-12-19 17:51:41 +00001133 >>> pairs = sorted(pairs)
Georg Brandld7413152009-10-11 21:25:26 +00001134 >>> pairs
Georg Brandl62eaaf62009-12-19 17:51:41 +00001135 [("I'm", 'else'), ('by', 'sort'), ('sorting', 'to'), ('what', 'something')]
1136 >>> result = [x[1] for x in pairs]
Georg Brandld7413152009-10-11 21:25:26 +00001137 >>> result
1138 ['else', 'sort', 'to', 'something']
1139
Georg Brandl62eaaf62009-12-19 17:51:41 +00001140
Georg Brandld7413152009-10-11 21:25:26 +00001141An alternative for the last step is::
1142
Georg Brandl62eaaf62009-12-19 17:51:41 +00001143 >>> result = []
1144 >>> for p in pairs: result.append(p[1])
Georg Brandld7413152009-10-11 21:25:26 +00001145
1146If you find this more legible, you might prefer to use this instead of the final
1147list comprehension. However, it is almost twice as slow for long lists. Why?
1148First, the ``append()`` operation has to reallocate memory, and while it uses
1149some tricks to avoid doing that each time, it still has to do it occasionally,
1150and that costs quite a bit. Second, the expression "result.append" requires an
1151extra attribute lookup, and third, there's a speed reduction from having to make
1152all those function calls.
1153
1154
1155Objects
1156=======
1157
1158What is a class?
1159----------------
1160
1161A class is the particular object type created by executing a class statement.
1162Class objects are used as templates to create instance objects, which embody
1163both the data (attributes) and code (methods) specific to a datatype.
1164
1165A class can be based on one or more other classes, called its base class(es). It
1166then inherits the attributes and methods of its base classes. This allows an
1167object model to be successively refined by inheritance. You might have a
1168generic ``Mailbox`` class that provides basic accessor methods for a mailbox,
1169and subclasses such as ``MboxMailbox``, ``MaildirMailbox``, ``OutlookMailbox``
1170that handle various specific mailbox formats.
1171
1172
1173What is a method?
1174-----------------
1175
1176A method is a function on some object ``x`` that you normally call as
1177``x.name(arguments...)``. Methods are defined as functions inside the class
1178definition::
1179
1180 class C:
1181 def meth (self, arg):
1182 return arg * 2 + self.attribute
1183
1184
1185What is self?
1186-------------
1187
1188Self is merely a conventional name for the first argument of a method. A method
1189defined as ``meth(self, a, b, c)`` should be called as ``x.meth(a, b, c)`` for
1190some instance ``x`` of the class in which the definition occurs; the called
1191method will think it is called as ``meth(x, a, b, c)``.
1192
1193See also :ref:`why-self`.
1194
1195
1196How do I check if an object is an instance of a given class or of a subclass of it?
1197-----------------------------------------------------------------------------------
1198
1199Use the built-in function ``isinstance(obj, cls)``. You can check if an object
1200is an instance of any of a number of classes by providing a tuple instead of a
1201single class, e.g. ``isinstance(obj, (class1, class2, ...))``, and can also
1202check whether an object is one of Python's built-in types, e.g.
Georg Brandl62eaaf62009-12-19 17:51:41 +00001203``isinstance(obj, str)`` or ``isinstance(obj, (int, float, complex))``.
Georg Brandld7413152009-10-11 21:25:26 +00001204
1205Note that most programs do not use :func:`isinstance` on user-defined classes
1206very often. If you are developing the classes yourself, a more proper
1207object-oriented style is to define methods on the classes that encapsulate a
1208particular behaviour, instead of checking the object's class and doing a
1209different thing based on what class it is. For example, if you have a function
1210that does something::
1211
Georg Brandl62eaaf62009-12-19 17:51:41 +00001212 def search(obj):
Georg Brandld7413152009-10-11 21:25:26 +00001213 if isinstance(obj, Mailbox):
1214 # ... code to search a mailbox
1215 elif isinstance(obj, Document):
1216 # ... code to search a document
1217 elif ...
1218
1219A better approach is to define a ``search()`` method on all the classes and just
1220call it::
1221
1222 class Mailbox:
1223 def search(self):
1224 # ... code to search a mailbox
1225
1226 class Document:
1227 def search(self):
1228 # ... code to search a document
1229
1230 obj.search()
1231
1232
1233What is delegation?
1234-------------------
1235
1236Delegation is an object oriented technique (also called a design pattern).
1237Let's say you have an object ``x`` and want to change the behaviour of just one
1238of its methods. You can create a new class that provides a new implementation
1239of the method you're interested in changing and delegates all other methods to
1240the corresponding method of ``x``.
1241
1242Python programmers can easily implement delegation. For example, the following
1243class implements a class that behaves like a file but converts all written data
1244to uppercase::
1245
1246 class UpperOut:
1247
1248 def __init__(self, outfile):
1249 self._outfile = outfile
1250
1251 def write(self, s):
1252 self._outfile.write(s.upper())
1253
1254 def __getattr__(self, name):
1255 return getattr(self._outfile, name)
1256
1257Here the ``UpperOut`` class redefines the ``write()`` method to convert the
1258argument string to uppercase before calling the underlying
1259``self.__outfile.write()`` method. All other methods are delegated to the
1260underlying ``self.__outfile`` object. The delegation is accomplished via the
1261``__getattr__`` method; consult :ref:`the language reference <attribute-access>`
1262for more information about controlling attribute access.
1263
1264Note that for more general cases delegation can get trickier. When attributes
1265must be set as well as retrieved, the class must define a :meth:`__setattr__`
1266method too, and it must do so carefully. The basic implementation of
1267:meth:`__setattr__` is roughly equivalent to the following::
1268
1269 class X:
1270 ...
1271 def __setattr__(self, name, value):
1272 self.__dict__[name] = value
1273 ...
1274
1275Most :meth:`__setattr__` implementations must modify ``self.__dict__`` to store
1276local state for self without causing an infinite recursion.
1277
1278
1279How do I call a method defined in a base class from a derived class that overrides it?
1280--------------------------------------------------------------------------------------
1281
Georg Brandl62eaaf62009-12-19 17:51:41 +00001282Use the built-in :func:`super` function::
Georg Brandld7413152009-10-11 21:25:26 +00001283
1284 class Derived(Base):
1285 def meth (self):
1286 super(Derived, self).meth()
1287
Georg Brandl62eaaf62009-12-19 17:51:41 +00001288For version prior to 3.0, you may be using classic classes: For a class
1289definition such as ``class Derived(Base): ...`` you can call method ``meth()``
1290defined in ``Base`` (or one of ``Base``'s base classes) as ``Base.meth(self,
1291arguments...)``. Here, ``Base.meth`` is an unbound method, so you need to
1292provide the ``self`` argument.
Georg Brandld7413152009-10-11 21:25:26 +00001293
1294
1295How can I organize my code to make it easier to change the base class?
1296----------------------------------------------------------------------
1297
1298You could define an alias for the base class, assign the real base class to it
1299before your class definition, and use the alias throughout your class. Then all
1300you have to change is the value assigned to the alias. Incidentally, this trick
1301is also handy if you want to decide dynamically (e.g. depending on availability
1302of resources) which base class to use. Example::
1303
1304 BaseAlias = <real base class>
1305
1306 class Derived(BaseAlias):
1307 def meth(self):
1308 BaseAlias.meth(self)
1309 ...
1310
1311
1312How do I create static class data and static class methods?
1313-----------------------------------------------------------
1314
Georg Brandl62eaaf62009-12-19 17:51:41 +00001315Both static data and static methods (in the sense of C++ or Java) are supported
1316in Python.
Georg Brandld7413152009-10-11 21:25:26 +00001317
1318For static data, simply define a class attribute. To assign a new value to the
1319attribute, you have to explicitly use the class name in the assignment::
1320
1321 class C:
1322 count = 0 # number of times C.__init__ called
1323
1324 def __init__(self):
1325 C.count = C.count + 1
1326
1327 def getcount(self):
1328 return C.count # or return self.count
1329
1330``c.count`` also refers to ``C.count`` for any ``c`` such that ``isinstance(c,
1331C)`` holds, unless overridden by ``c`` itself or by some class on the base-class
1332search path from ``c.__class__`` back to ``C``.
1333
1334Caution: within a method of C, an assignment like ``self.count = 42`` creates a
Georg Brandl62eaaf62009-12-19 17:51:41 +00001335new and unrelated instance named "count" in ``self``'s own dict. Rebinding of a
1336class-static data name must always specify the class whether inside a method or
1337not::
Georg Brandld7413152009-10-11 21:25:26 +00001338
1339 C.count = 314
1340
Antoine Pitrouf3520402011-12-03 22:19:55 +01001341Static methods are possible::
Georg Brandld7413152009-10-11 21:25:26 +00001342
1343 class C:
1344 @staticmethod
1345 def static(arg1, arg2, arg3):
1346 # No 'self' parameter!
1347 ...
1348
1349However, a far more straightforward way to get the effect of a static method is
1350via a simple module-level function::
1351
1352 def getcount():
1353 return C.count
1354
1355If your code is structured so as to define one class (or tightly related class
1356hierarchy) per module, this supplies the desired encapsulation.
1357
1358
1359How can I overload constructors (or methods) in Python?
1360-------------------------------------------------------
1361
1362This answer actually applies to all methods, but the question usually comes up
1363first in the context of constructors.
1364
1365In C++ you'd write
1366
1367.. code-block:: c
1368
1369 class C {
1370 C() { cout << "No arguments\n"; }
1371 C(int i) { cout << "Argument is " << i << "\n"; }
1372 }
1373
1374In Python you have to write a single constructor that catches all cases using
1375default arguments. For example::
1376
1377 class C:
1378 def __init__(self, i=None):
1379 if i is None:
Georg Brandl62eaaf62009-12-19 17:51:41 +00001380 print("No arguments")
Georg Brandld7413152009-10-11 21:25:26 +00001381 else:
Georg Brandl62eaaf62009-12-19 17:51:41 +00001382 print("Argument is", i)
Georg Brandld7413152009-10-11 21:25:26 +00001383
1384This is not entirely equivalent, but close enough in practice.
1385
1386You could also try a variable-length argument list, e.g. ::
1387
1388 def __init__(self, *args):
1389 ...
1390
1391The same approach works for all method definitions.
1392
1393
1394I try to use __spam and I get an error about _SomeClassName__spam.
1395------------------------------------------------------------------
1396
1397Variable names with double leading underscores are "mangled" to provide a simple
1398but effective way to define class private variables. Any identifier of the form
1399``__spam`` (at least two leading underscores, at most one trailing underscore)
1400is textually replaced with ``_classname__spam``, where ``classname`` is the
1401current class name with any leading underscores stripped.
1402
1403This doesn't guarantee privacy: an outside user can still deliberately access
1404the "_classname__spam" attribute, and private values are visible in the object's
1405``__dict__``. Many Python programmers never bother to use private variable
1406names at all.
1407
1408
1409My class defines __del__ but it is not called when I delete the object.
1410-----------------------------------------------------------------------
1411
1412There are several possible reasons for this.
1413
1414The del statement does not necessarily call :meth:`__del__` -- it simply
1415decrements the object's reference count, and if this reaches zero
1416:meth:`__del__` is called.
1417
1418If your data structures contain circular links (e.g. a tree where each child has
1419a parent reference and each parent has a list of children) the reference counts
1420will never go back to zero. Once in a while Python runs an algorithm to detect
1421such cycles, but the garbage collector might run some time after the last
1422reference to your data structure vanishes, so your :meth:`__del__` method may be
1423called at an inconvenient and random time. This is inconvenient if you're trying
1424to reproduce a problem. Worse, the order in which object's :meth:`__del__`
1425methods are executed is arbitrary. You can run :func:`gc.collect` to force a
1426collection, but there *are* pathological cases where objects will never be
1427collected.
1428
1429Despite the cycle collector, it's still a good idea to define an explicit
1430``close()`` method on objects to be called whenever you're done with them. The
1431``close()`` method can then remove attributes that refer to subobjecs. Don't
1432call :meth:`__del__` directly -- :meth:`__del__` should call ``close()`` and
1433``close()`` should make sure that it can be called more than once for the same
1434object.
1435
1436Another way to avoid cyclical references is to use the :mod:`weakref` module,
1437which allows you to point to objects without incrementing their reference count.
1438Tree data structures, for instance, should use weak references for their parent
1439and sibling references (if they need them!).
1440
Georg Brandl62eaaf62009-12-19 17:51:41 +00001441.. XXX relevant for Python 3?
1442
1443 If the object has ever been a local variable in a function that caught an
1444 expression in an except clause, chances are that a reference to the object
1445 still exists in that function's stack frame as contained in the stack trace.
1446 Normally, calling :func:`sys.exc_clear` will take care of this by clearing
1447 the last recorded exception.
Georg Brandld7413152009-10-11 21:25:26 +00001448
1449Finally, if your :meth:`__del__` method raises an exception, a warning message
1450is printed to :data:`sys.stderr`.
1451
1452
1453How do I get a list of all instances of a given class?
1454------------------------------------------------------
1455
1456Python does not keep track of all instances of a class (or of a built-in type).
1457You can program the class's constructor to keep track of all instances by
1458keeping a list of weak references to each instance.
1459
1460
1461Modules
1462=======
1463
1464How do I create a .pyc file?
1465----------------------------
1466
1467When a module is imported for the first time (or when the source is more recent
1468than the current compiled file) a ``.pyc`` file containing the compiled code
1469should be created in the same directory as the ``.py`` file.
1470
1471One reason that a ``.pyc`` file may not be created is permissions problems with
1472the directory. This can happen, for example, if you develop as one user but run
1473as another, such as if you are testing with a web server. Creation of a .pyc
1474file is automatic if you're importing a module and Python has the ability
1475(permissions, free space, etc...) to write the compiled module back to the
1476directory.
1477
1478Running Python on a top level script is not considered an import and no ``.pyc``
1479will be created. For example, if you have a top-level module ``abc.py`` that
1480imports another module ``xyz.py``, when you run abc, ``xyz.pyc`` will be created
1481since xyz is imported, but no ``abc.pyc`` file will be created since ``abc.py``
1482isn't being imported.
1483
1484If you need to create abc.pyc -- that is, to create a .pyc file for a module
1485that is not imported -- you can, using the :mod:`py_compile` and
1486:mod:`compileall` modules.
1487
1488The :mod:`py_compile` module can manually compile any module. One way is to use
1489the ``compile()`` function in that module interactively::
1490
1491 >>> import py_compile
1492 >>> py_compile.compile('abc.py')
1493
1494This will write the ``.pyc`` to the same location as ``abc.py`` (or you can
1495override that with the optional parameter ``cfile``).
1496
1497You can also automatically compile all files in a directory or directories using
1498the :mod:`compileall` module. You can do it from the shell prompt by running
1499``compileall.py`` and providing the path of a directory containing Python files
1500to compile::
1501
1502 python -m compileall .
1503
1504
1505How do I find the current module name?
1506--------------------------------------
1507
1508A module can find out its own module name by looking at the predefined global
1509variable ``__name__``. If this has the value ``'__main__'``, the program is
1510running as a script. Many modules that are usually used by importing them also
1511provide a command-line interface or a self-test, and only execute this code
1512after checking ``__name__``::
1513
1514 def main():
Georg Brandl62eaaf62009-12-19 17:51:41 +00001515 print('Running test...')
Georg Brandld7413152009-10-11 21:25:26 +00001516 ...
1517
1518 if __name__ == '__main__':
1519 main()
1520
1521
1522How can I have modules that mutually import each other?
1523-------------------------------------------------------
1524
1525Suppose you have the following modules:
1526
1527foo.py::
1528
1529 from bar import bar_var
1530 foo_var = 1
1531
1532bar.py::
1533
1534 from foo import foo_var
1535 bar_var = 2
1536
1537The problem is that the interpreter will perform the following steps:
1538
1539* main imports foo
1540* Empty globals for foo are created
1541* foo is compiled and starts executing
1542* foo imports bar
1543* Empty globals for bar are created
1544* bar is compiled and starts executing
1545* bar imports foo (which is a no-op since there already is a module named foo)
1546* bar.foo_var = foo.foo_var
1547
1548The last step fails, because Python isn't done with interpreting ``foo`` yet and
1549the global symbol dictionary for ``foo`` is still empty.
1550
1551The same thing happens when you use ``import foo``, and then try to access
1552``foo.foo_var`` in global code.
1553
1554There are (at least) three possible workarounds for this problem.
1555
1556Guido van Rossum recommends avoiding all uses of ``from <module> import ...``,
1557and placing all code inside functions. Initializations of global variables and
1558class variables should use constants or built-in functions only. This means
1559everything from an imported module is referenced as ``<module>.<name>``.
1560
1561Jim Roskind suggests performing steps in the following order in each module:
1562
1563* exports (globals, functions, and classes that don't need imported base
1564 classes)
1565* ``import`` statements
1566* active code (including globals that are initialized from imported values).
1567
1568van Rossum doesn't like this approach much because the imports appear in a
1569strange place, but it does work.
1570
1571Matthias Urlichs recommends restructuring your code so that the recursive import
1572is not necessary in the first place.
1573
1574These solutions are not mutually exclusive.
1575
1576
1577__import__('x.y.z') returns <module 'x'>; how do I get z?
1578---------------------------------------------------------
1579
1580Try::
1581
1582 __import__('x.y.z').y.z
1583
1584For more realistic situations, you may have to do something like ::
1585
1586 m = __import__(s)
1587 for i in s.split(".")[1:]:
1588 m = getattr(m, i)
1589
1590See :mod:`importlib` for a convenience function called
1591:func:`~importlib.import_module`.
1592
1593
1594
1595When I edit an imported module and reimport it, the changes don't show up. Why does this happen?
1596-------------------------------------------------------------------------------------------------
1597
1598For reasons of efficiency as well as consistency, Python only reads the module
1599file on the first time a module is imported. If it didn't, in a program
1600consisting of many modules where each one imports the same basic module, the
1601basic module would be parsed and re-parsed many times. To force rereading of a
1602changed module, do this::
1603
Georg Brandl62eaaf62009-12-19 17:51:41 +00001604 import imp
Georg Brandld7413152009-10-11 21:25:26 +00001605 import modname
Georg Brandl62eaaf62009-12-19 17:51:41 +00001606 imp.reload(modname)
Georg Brandld7413152009-10-11 21:25:26 +00001607
1608Warning: this technique is not 100% fool-proof. In particular, modules
1609containing statements like ::
1610
1611 from modname import some_objects
1612
1613will continue to work with the old version of the imported objects. If the
1614module contains class definitions, existing class instances will *not* be
1615updated to use the new class definition. This can result in the following
1616paradoxical behaviour:
1617
Georg Brandl62eaaf62009-12-19 17:51:41 +00001618 >>> import imp
Georg Brandld7413152009-10-11 21:25:26 +00001619 >>> import cls
1620 >>> c = cls.C() # Create an instance of C
Georg Brandl62eaaf62009-12-19 17:51:41 +00001621 >>> imp.reload(cls)
1622 <module 'cls' from 'cls.py'>
Georg Brandld7413152009-10-11 21:25:26 +00001623 >>> isinstance(c, cls.C) # isinstance is false?!?
1624 False
1625
Georg Brandl62eaaf62009-12-19 17:51:41 +00001626The nature of the problem is made clear if you print out the "identity" of the
1627class objects:
Georg Brandld7413152009-10-11 21:25:26 +00001628
Georg Brandl62eaaf62009-12-19 17:51:41 +00001629 >>> hex(id(c.__class__))
1630 '0x7352a0'
1631 >>> hex(id(cls.C))
1632 '0x4198d0'