blob: d33e25be85f50fc8f8e2166780b8a995b907b914 [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
316How do I write a function with output parameters (call by reference)?
317---------------------------------------------------------------------
318
319Remember that arguments are passed by assignment in Python. Since assignment
320just creates references to objects, there's no alias between an argument name in
321the caller and callee, and so no call-by-reference per se. You can achieve the
322desired effect in a number of ways.
323
3241) By returning a tuple of the results::
325
326 def func2(a, b):
327 a = 'new-value' # a and b are local names
328 b = b + 1 # assigned to new objects
329 return a, b # return new values
330
331 x, y = 'old-value', 99
332 x, y = func2(x, y)
Georg Brandl62eaaf62009-12-19 17:51:41 +0000333 print(x, y) # output: new-value 100
Georg Brandld7413152009-10-11 21:25:26 +0000334
335 This is almost always the clearest solution.
336
3372) By using global variables. This isn't thread-safe, and is not recommended.
338
3393) By passing a mutable (changeable in-place) object::
340
341 def func1(a):
342 a[0] = 'new-value' # 'a' references a mutable list
343 a[1] = a[1] + 1 # changes a shared object
344
345 args = ['old-value', 99]
346 func1(args)
Georg Brandl62eaaf62009-12-19 17:51:41 +0000347 print(args[0], args[1]) # output: new-value 100
Georg Brandld7413152009-10-11 21:25:26 +0000348
3494) By passing in a dictionary that gets mutated::
350
351 def func3(args):
352 args['a'] = 'new-value' # args is a mutable dictionary
353 args['b'] = args['b'] + 1 # change it in-place
354
355 args = {'a':' old-value', 'b': 99}
356 func3(args)
Georg Brandl62eaaf62009-12-19 17:51:41 +0000357 print(args['a'], args['b'])
Georg Brandld7413152009-10-11 21:25:26 +0000358
3595) Or bundle up values in a class instance::
360
361 class callByRef:
362 def __init__(self, **args):
363 for (key, value) in args.items():
364 setattr(self, key, value)
365
366 def func4(args):
367 args.a = 'new-value' # args is a mutable callByRef
368 args.b = args.b + 1 # change object in-place
369
370 args = callByRef(a='old-value', b=99)
371 func4(args)
Georg Brandl62eaaf62009-12-19 17:51:41 +0000372 print(args.a, args.b)
Georg Brandld7413152009-10-11 21:25:26 +0000373
374
375 There's almost never a good reason to get this complicated.
376
377Your best choice is to return a tuple containing the multiple results.
378
379
380How do you make a higher order function in Python?
381--------------------------------------------------
382
383You have two choices: you can use nested scopes or you can use callable objects.
384For example, suppose you wanted to define ``linear(a,b)`` which returns a
385function ``f(x)`` that computes the value ``a*x+b``. Using nested scopes::
386
387 def linear(a, b):
388 def result(x):
389 return a * x + b
390 return result
391
392Or using a callable object::
393
394 class linear:
395
396 def __init__(self, a, b):
397 self.a, self.b = a, b
398
399 def __call__(self, x):
400 return self.a * x + self.b
401
402In both cases, ::
403
404 taxes = linear(0.3, 2)
405
406gives a callable object where ``taxes(10e6) == 0.3 * 10e6 + 2``.
407
408The callable object approach has the disadvantage that it is a bit slower and
409results in slightly longer code. However, note that a collection of callables
410can share their signature via inheritance::
411
412 class exponential(linear):
413 # __init__ inherited
414 def __call__(self, x):
415 return self.a * (x ** self.b)
416
417Object can encapsulate state for several methods::
418
419 class counter:
420
421 value = 0
422
423 def set(self, x):
424 self.value = x
425
426 def up(self):
427 self.value = self.value + 1
428
429 def down(self):
430 self.value = self.value - 1
431
432 count = counter()
433 inc, dec, reset = count.up, count.down, count.set
434
435Here ``inc()``, ``dec()`` and ``reset()`` act like functions which share the
436same counting variable.
437
438
439How do I copy an object in Python?
440----------------------------------
441
442In general, try :func:`copy.copy` or :func:`copy.deepcopy` for the general case.
443Not all objects can be copied, but most can.
444
445Some objects can be copied more easily. Dictionaries have a :meth:`~dict.copy`
446method::
447
448 newdict = olddict.copy()
449
450Sequences can be copied by slicing::
451
452 new_l = l[:]
453
454
455How can I find the methods or attributes of an object?
456------------------------------------------------------
457
458For an instance x of a user-defined class, ``dir(x)`` returns an alphabetized
459list of the names containing the instance attributes and methods and attributes
460defined by its class.
461
462
463How can my code discover the name of an object?
464-----------------------------------------------
465
466Generally speaking, it can't, because objects don't really have names.
467Essentially, assignment always binds a name to a value; The same is true of
468``def`` and ``class`` statements, but in that case the value is a
469callable. Consider the following code::
470
471 class A:
472 pass
473
474 B = A
475
476 a = B()
477 b = a
Georg Brandl62eaaf62009-12-19 17:51:41 +0000478 print(b)
479 <__main__.A object at 0x16D07CC>
480 print(a)
481 <__main__.A object at 0x16D07CC>
Georg Brandld7413152009-10-11 21:25:26 +0000482
483Arguably the class has a name: even though it is bound to two names and invoked
484through the name B the created instance is still reported as an instance of
485class A. However, it is impossible to say whether the instance's name is a or
486b, since both names are bound to the same value.
487
488Generally speaking it should not be necessary for your code to "know the names"
489of particular values. Unless you are deliberately writing introspective
490programs, this is usually an indication that a change of approach might be
491beneficial.
492
493In comp.lang.python, Fredrik Lundh once gave an excellent analogy in answer to
494this question:
495
496 The same way as you get the name of that cat you found on your porch: the cat
497 (object) itself cannot tell you its name, and it doesn't really care -- so
498 the only way to find out what it's called is to ask all your neighbours
499 (namespaces) if it's their cat (object)...
500
501 ....and don't be surprised if you'll find that it's known by many names, or
502 no name at all!
503
504
505What's up with the comma operator's precedence?
506-----------------------------------------------
507
508Comma is not an operator in Python. Consider this session::
509
510 >>> "a" in "b", "a"
Georg Brandl62eaaf62009-12-19 17:51:41 +0000511 (False, 'a')
Georg Brandld7413152009-10-11 21:25:26 +0000512
513Since the comma is not an operator, but a separator between expressions the
514above is evaluated as if you had entered::
515
516 >>> ("a" in "b"), "a"
517
518not::
519
Georg Brandl62eaaf62009-12-19 17:51:41 +0000520 >>> "a" in ("b", "a")
Georg Brandld7413152009-10-11 21:25:26 +0000521
522The same is true of the various assignment operators (``=``, ``+=`` etc). They
523are not truly operators but syntactic delimiters in assignment statements.
524
525
526Is there an equivalent of C's "?:" ternary operator?
527----------------------------------------------------
528
Antoine Pitrouc5b266e2011-12-03 22:11:11 +0100529Yes, there is. The syntax is as follows::
Georg Brandld7413152009-10-11 21:25:26 +0000530
531 [on_true] if [expression] else [on_false]
532
533 x, y = 50, 25
Georg Brandld7413152009-10-11 21:25:26 +0000534 small = x if x < y else y
535
Antoine Pitrouc5b266e2011-12-03 22:11:11 +0100536Before this syntax was introduced in Python 2.5, a common idiom was to use
537logical operators::
Georg Brandld7413152009-10-11 21:25:26 +0000538
Antoine Pitrouc5b266e2011-12-03 22:11:11 +0100539 [expression] and [on_true] or [on_false]
Georg Brandld7413152009-10-11 21:25:26 +0000540
Antoine Pitrouc5b266e2011-12-03 22:11:11 +0100541However, this idiom is unsafe, as it can give wrong results when *on_true*
542has a false boolean value. Therefore, it is always better to use
543the ``... if ... else ...`` form.
Georg Brandld7413152009-10-11 21:25:26 +0000544
545
546Is it possible to write obfuscated one-liners in Python?
547--------------------------------------------------------
548
549Yes. Usually this is done by nesting :keyword:`lambda` within
550:keyword:`lambda`. See the following three examples, due to Ulf Bartelt::
551
Georg Brandl62eaaf62009-12-19 17:51:41 +0000552 from functools import reduce
553
Georg Brandld7413152009-10-11 21:25:26 +0000554 # Primes < 1000
Georg Brandl62eaaf62009-12-19 17:51:41 +0000555 print(list(filter(None,map(lambda y:y*reduce(lambda x,y:x*y!=0,
556 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 +0000557
558 # First 10 Fibonacci numbers
Georg Brandl62eaaf62009-12-19 17:51:41 +0000559 print(list(map(lambda x,f=lambda x,f:(f(x-1,f)+f(x-2,f)) if x>1 else 1:
560 f(x,f), range(10))))
Georg Brandld7413152009-10-11 21:25:26 +0000561
562 # Mandelbrot set
Georg Brandl62eaaf62009-12-19 17:51:41 +0000563 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 +0000564 Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,Sy=Sy,L=lambda yc,Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,i=IM,
565 Sx=Sx,Sy=Sy:reduce(lambda x,y:x+y,map(lambda x,xc=Ru,yc=yc,Ru=Ru,Ro=Ro,
566 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
567 >=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(
568 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 +0000569 ))))(-2.1, 0.7, -1.2, 1.2, 30, 80, 24))
Georg Brandld7413152009-10-11 21:25:26 +0000570 # \___ ___/ \___ ___/ | | |__ lines on screen
571 # V V | |______ columns on screen
572 # | | |__________ maximum of "iterations"
573 # | |_________________ range on y axis
574 # |____________________________ range on x axis
575
576Don't try this at home, kids!
577
578
579Numbers and strings
580===================
581
582How do I specify hexadecimal and octal integers?
583------------------------------------------------
584
Georg Brandl62eaaf62009-12-19 17:51:41 +0000585To specify an octal digit, precede the octal value with a zero, and then a lower
586or uppercase "o". For example, to set the variable "a" to the octal value "10"
587(8 in decimal), type::
Georg Brandld7413152009-10-11 21:25:26 +0000588
Georg Brandl62eaaf62009-12-19 17:51:41 +0000589 >>> a = 0o10
Georg Brandld7413152009-10-11 21:25:26 +0000590 >>> a
591 8
592
593Hexadecimal is just as easy. Simply precede the hexadecimal number with a zero,
594and then a lower or uppercase "x". Hexadecimal digits can be specified in lower
595or uppercase. For example, in the Python interpreter::
596
597 >>> a = 0xa5
598 >>> a
599 165
600 >>> b = 0XB2
601 >>> b
602 178
603
604
Georg Brandl62eaaf62009-12-19 17:51:41 +0000605Why does -22 // 10 return -3?
606-----------------------------
Georg Brandld7413152009-10-11 21:25:26 +0000607
608It's primarily driven by the desire that ``i % j`` have the same sign as ``j``.
609If you want that, and also want::
610
Georg Brandl62eaaf62009-12-19 17:51:41 +0000611 i == (i // j) * j + (i % j)
Georg Brandld7413152009-10-11 21:25:26 +0000612
613then integer division has to return the floor. C also requires that identity to
Georg Brandl62eaaf62009-12-19 17:51:41 +0000614hold, and then compilers that truncate ``i // j`` need to make ``i % j`` have
615the same sign as ``i``.
Georg Brandld7413152009-10-11 21:25:26 +0000616
617There are few real use cases for ``i % j`` when ``j`` is negative. When ``j``
618is positive, there are many, and in virtually all of them it's more useful for
619``i % j`` to be ``>= 0``. If the clock says 10 now, what did it say 200 hours
620ago? ``-190 % 12 == 2`` is useful; ``-190 % 12 == -10`` is a bug waiting to
621bite.
622
623
624How do I convert a string to a number?
625--------------------------------------
626
627For integers, use the built-in :func:`int` type constructor, e.g. ``int('144')
628== 144``. Similarly, :func:`float` converts to floating-point,
629e.g. ``float('144') == 144.0``.
630
631By default, these interpret the number as decimal, so that ``int('0144') ==
632144`` and ``int('0x144')`` raises :exc:`ValueError`. ``int(string, base)`` takes
633the base to convert from as a second optional argument, so ``int('0x144', 16) ==
634324``. If the base is specified as 0, the number is interpreted using Python's
635rules: a leading '0' indicates octal, and '0x' indicates a hex number.
636
637Do not use the built-in function :func:`eval` if all you need is to convert
638strings to numbers. :func:`eval` will be significantly slower and it presents a
639security risk: someone could pass you a Python expression that might have
640unwanted side effects. For example, someone could pass
641``__import__('os').system("rm -rf $HOME")`` which would erase your home
642directory.
643
644:func:`eval` also has the effect of interpreting numbers as Python expressions,
Georg Brandl62eaaf62009-12-19 17:51:41 +0000645so that e.g. ``eval('09')`` gives a syntax error because Python does not allow
646leading '0' in a decimal number (except '0').
Georg Brandld7413152009-10-11 21:25:26 +0000647
648
649How do I convert a number to a string?
650--------------------------------------
651
652To convert, e.g., the number 144 to the string '144', use the built-in type
653constructor :func:`str`. If you want a hexadecimal or octal representation, use
Georg Brandl62eaaf62009-12-19 17:51:41 +0000654the built-in functions :func:`hex` or :func:`oct`. For fancy formatting, see
655the :ref:`string-formatting` section, e.g. ``"{:04d}".format(144)`` yields
Georg Brandl11b63622009-12-20 14:21:27 +0000656``'0144'`` and ``"{:.3f}".format(1/3)`` yields ``'0.333'``.
Georg Brandld7413152009-10-11 21:25:26 +0000657
658
659How do I modify a string in place?
660----------------------------------
661
Antoine Pitrouc5b266e2011-12-03 22:11:11 +0100662You can't, because strings are immutable. In most situations, you should
663simply construct a new string from the various parts you want to assemble
664it from. However, if you need an object with the ability to modify in-place
665unicode data, try using a :class:`io.StringIO` object or the :mod:`array`
666module::
Georg Brandld7413152009-10-11 21:25:26 +0000667
668 >>> s = "Hello, world"
Antoine Pitrouc5b266e2011-12-03 22:11:11 +0100669 >>> sio = io.StringIO(s)
670 >>> sio.getvalue()
671 'Hello, world'
672 >>> sio.seek(7)
673 7
674 >>> sio.write("there!")
675 6
676 >>> sio.getvalue()
Georg Brandld7413152009-10-11 21:25:26 +0000677 'Hello, there!'
678
679 >>> import array
Georg Brandl62eaaf62009-12-19 17:51:41 +0000680 >>> a = array.array('u', s)
681 >>> print(a)
682 array('u', 'Hello, world')
683 >>> a[0] = 'y'
684 >>> print(a)
685 array('u', 'yello world')
686 >>> a.tounicode()
Georg Brandld7413152009-10-11 21:25:26 +0000687 'yello, world'
688
689
690How do I use strings to call functions/methods?
691-----------------------------------------------
692
693There are various techniques.
694
695* The best is to use a dictionary that maps strings to functions. The primary
696 advantage of this technique is that the strings do not need to match the names
697 of the functions. This is also the primary technique used to emulate a case
698 construct::
699
700 def a():
701 pass
702
703 def b():
704 pass
705
706 dispatch = {'go': a, 'stop': b} # Note lack of parens for funcs
707
708 dispatch[get_input()]() # Note trailing parens to call function
709
710* Use the built-in function :func:`getattr`::
711
712 import foo
713 getattr(foo, 'bar')()
714
715 Note that :func:`getattr` works on any object, including classes, class
716 instances, modules, and so on.
717
718 This is used in several places in the standard library, like this::
719
720 class Foo:
721 def do_foo(self):
722 ...
723
724 def do_bar(self):
725 ...
726
727 f = getattr(foo_instance, 'do_' + opname)
728 f()
729
730
731* Use :func:`locals` or :func:`eval` to resolve the function name::
732
733 def myFunc():
Georg Brandl62eaaf62009-12-19 17:51:41 +0000734 print("hello")
Georg Brandld7413152009-10-11 21:25:26 +0000735
736 fname = "myFunc"
737
738 f = locals()[fname]
739 f()
740
741 f = eval(fname)
742 f()
743
744 Note: Using :func:`eval` is slow and dangerous. If you don't have absolute
745 control over the contents of the string, someone could pass a string that
746 resulted in an arbitrary function being executed.
747
748Is there an equivalent to Perl's chomp() for removing trailing newlines from strings?
749-------------------------------------------------------------------------------------
750
Antoine Pitrouf3520402011-12-03 22:19:55 +0100751You can use ``S.rstrip("\r\n")`` to remove all occurrences of any line
752terminator from the end of the string ``S`` without removing other trailing
753whitespace. If the string ``S`` represents more than one line, with several
754empty lines at the end, the line terminators for all the blank lines will
755be removed::
Georg Brandld7413152009-10-11 21:25:26 +0000756
757 >>> lines = ("line 1 \r\n"
758 ... "\r\n"
759 ... "\r\n")
760 >>> lines.rstrip("\n\r")
Georg Brandl62eaaf62009-12-19 17:51:41 +0000761 'line 1 '
Georg Brandld7413152009-10-11 21:25:26 +0000762
763Since this is typically only desired when reading text one line at a time, using
764``S.rstrip()`` this way works well.
765
Georg Brandld7413152009-10-11 21:25:26 +0000766
767Is there a scanf() or sscanf() equivalent?
768------------------------------------------
769
770Not as such.
771
772For simple input parsing, the easiest approach is usually to split the line into
773whitespace-delimited words using the :meth:`~str.split` method of string objects
774and then convert decimal strings to numeric values using :func:`int` or
775:func:`float`. ``split()`` supports an optional "sep" parameter which is useful
776if the line uses something other than whitespace as a separator.
777
Brian Curtin5a7a52f2010-09-23 13:45:21 +0000778For more complicated input parsing, regular expressions are more powerful
Georg Brandl60203b42010-10-06 10:11:56 +0000779than C's :c:func:`sscanf` and better suited for the task.
Georg Brandld7413152009-10-11 21:25:26 +0000780
781
Georg Brandl62eaaf62009-12-19 17:51:41 +0000782What does 'UnicodeDecodeError' or 'UnicodeEncodeError' error mean?
783-------------------------------------------------------------------
Georg Brandld7413152009-10-11 21:25:26 +0000784
Georg Brandl62eaaf62009-12-19 17:51:41 +0000785See the :ref:`unicode-howto`.
Georg Brandld7413152009-10-11 21:25:26 +0000786
787
Antoine Pitrou432259f2011-12-09 23:10:31 +0100788Performance
789===========
790
791My program is too slow. How do I speed it up?
792---------------------------------------------
793
794That's a tough one, in general. First, here are a list of things to
795remember before diving further:
796
Georg Brandl300a6912012-03-14 22:40:08 +0100797* Performance characteristics vary across Python implementations. This FAQ
Antoine Pitrou432259f2011-12-09 23:10:31 +0100798 focusses on :term:`CPython`.
Georg Brandl300a6912012-03-14 22:40:08 +0100799* Behaviour can vary across operating systems, especially when talking about
Antoine Pitrou432259f2011-12-09 23:10:31 +0100800 I/O or multi-threading.
801* You should always find the hot spots in your program *before* attempting to
802 optimize any code (see the :mod:`profile` module).
803* Writing benchmark scripts will allow you to iterate quickly when searching
804 for improvements (see the :mod:`timeit` module).
805* It is highly recommended to have good code coverage (through unit testing
806 or any other technique) before potentially introducing regressions hidden
807 in sophisticated optimizations.
808
809That being said, there are many tricks to speed up Python code. Here are
810some general principles which go a long way towards reaching acceptable
811performance levels:
812
813* Making your algorithms faster (or changing to faster ones) can yield
814 much larger benefits than trying to sprinkle micro-optimization tricks
815 all over your code.
816
817* Use the right data structures. Study documentation for the :ref:`bltin-types`
818 and the :mod:`collections` module.
819
820* When the standard library provides a primitive for doing something, it is
821 likely (although not guaranteed) to be faster than any alternative you
822 may come up with. This is doubly true for primitives written in C, such
823 as builtins and some extension types. For example, be sure to use
824 either the :meth:`list.sort` built-in method or the related :func:`sorted`
825 function to do sorting (and see the
826 `sorting mini-HOWTO <http://wiki.python.org/moin/HowTo/Sorting>`_ for examples
827 of moderately advanced usage).
828
829* Abstractions tend to create indirections and force the interpreter to work
830 more. If the levels of indirection outweigh the amount of useful work
831 done, your program will be slower. You should avoid excessive abstraction,
832 especially under the form of tiny functions or methods (which are also often
833 detrimental to readability).
834
835If you have reached the limit of what pure Python can allow, there are tools
836to take you further away. For example, `Cython <http://cython.org>`_ can
837compile a slightly modified version of Python code into a C extension, and
838can be used on many different platforms. Cython can take advantage of
839compilation (and optional type annotations) to make your code significantly
840faster than when interpreted. If you are confident in your C programming
841skills, you can also :ref:`write a C extension module <extending-index>`
842yourself.
843
844.. seealso::
845 The wiki page devoted to `performance tips
846 <http://wiki.python.org/moin/PythonSpeed/PerformanceTips>`_.
847
848.. _efficient_string_concatenation:
849
Antoine Pitroufd9ebd42011-11-25 16:33:53 +0100850What is the most efficient way to concatenate many strings together?
851--------------------------------------------------------------------
852
853:class:`str` and :class:`bytes` objects are immutable, therefore concatenating
854many strings together is inefficient as each concatenation creates a new
855object. In the general case, the total runtime cost is quadratic in the
856total string length.
857
858To accumulate many :class:`str` objects, the recommended idiom is to place
859them into a list and call :meth:`str.join` at the end::
860
861 chunks = []
862 for s in my_strings:
863 chunks.append(s)
864 result = ''.join(chunks)
865
866(another reasonably efficient idiom is to use :class:`io.StringIO`)
867
868To accumulate many :class:`bytes` objects, the recommended idiom is to extend
869a :class:`bytearray` object using in-place concatenation (the ``+=`` operator)::
870
871 result = bytearray()
872 for b in my_bytes_objects:
873 result += b
874
875
Georg Brandld7413152009-10-11 21:25:26 +0000876Sequences (Tuples/Lists)
877========================
878
879How do I convert between tuples and lists?
880------------------------------------------
881
882The type constructor ``tuple(seq)`` converts any sequence (actually, any
883iterable) into a tuple with the same items in the same order.
884
885For example, ``tuple([1, 2, 3])`` yields ``(1, 2, 3)`` and ``tuple('abc')``
886yields ``('a', 'b', 'c')``. If the argument is a tuple, it does not make a copy
887but returns the same object, so it is cheap to call :func:`tuple` when you
888aren't sure that an object is already a tuple.
889
890The type constructor ``list(seq)`` converts any sequence or iterable into a list
891with the same items in the same order. For example, ``list((1, 2, 3))`` yields
892``[1, 2, 3]`` and ``list('abc')`` yields ``['a', 'b', 'c']``. If the argument
893is a list, it makes a copy just like ``seq[:]`` would.
894
895
896What's a negative index?
897------------------------
898
899Python sequences are indexed with positive numbers and negative numbers. For
900positive numbers 0 is the first index 1 is the second index and so forth. For
901negative indices -1 is the last index and -2 is the penultimate (next to last)
902index and so forth. Think of ``seq[-n]`` as the same as ``seq[len(seq)-n]``.
903
904Using negative indices can be very convenient. For example ``S[:-1]`` is all of
905the string except for its last character, which is useful for removing the
906trailing newline from a string.
907
908
909How do I iterate over a sequence in reverse order?
910--------------------------------------------------
911
Georg Brandlc4a55fc2010-02-06 18:46:57 +0000912Use the :func:`reversed` built-in function, which is new in Python 2.4::
Georg Brandld7413152009-10-11 21:25:26 +0000913
914 for x in reversed(sequence):
915 ... # do something with x...
916
917This won't touch your original sequence, but build a new copy with reversed
918order to iterate over.
919
920With Python 2.3, you can use an extended slice syntax::
921
922 for x in sequence[::-1]:
923 ... # do something with x...
924
925
926How do you remove duplicates from a list?
927-----------------------------------------
928
929See the Python Cookbook for a long discussion of many ways to do this:
930
931 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52560
932
933If you don't mind reordering the list, sort it and then scan from the end of the
934list, deleting duplicates as you go::
935
Georg Brandl62eaaf62009-12-19 17:51:41 +0000936 if mylist:
937 mylist.sort()
938 last = mylist[-1]
939 for i in range(len(mylist)-2, -1, -1):
940 if last == mylist[i]:
941 del mylist[i]
Georg Brandld7413152009-10-11 21:25:26 +0000942 else:
Georg Brandl62eaaf62009-12-19 17:51:41 +0000943 last = mylist[i]
Georg Brandld7413152009-10-11 21:25:26 +0000944
Antoine Pitrouf3520402011-12-03 22:19:55 +0100945If all elements of the list may be used as set keys (i.e. they are all
946:term:`hashable`) this is often faster ::
Georg Brandld7413152009-10-11 21:25:26 +0000947
Georg Brandl62eaaf62009-12-19 17:51:41 +0000948 mylist = list(set(mylist))
Georg Brandld7413152009-10-11 21:25:26 +0000949
950This converts the list into a set, thereby removing duplicates, and then back
951into a list.
952
953
954How do you make an array in Python?
955-----------------------------------
956
957Use a list::
958
959 ["this", 1, "is", "an", "array"]
960
961Lists are equivalent to C or Pascal arrays in their time complexity; the primary
962difference is that a Python list can contain objects of many different types.
963
964The ``array`` module also provides methods for creating arrays of fixed types
965with compact representations, but they are slower to index than lists. Also
966note that the Numeric extensions and others define array-like structures with
967various characteristics as well.
968
969To get Lisp-style linked lists, you can emulate cons cells using tuples::
970
971 lisp_list = ("like", ("this", ("example", None) ) )
972
973If mutability is desired, you could use lists instead of tuples. Here the
974analogue of lisp car is ``lisp_list[0]`` and the analogue of cdr is
975``lisp_list[1]``. Only do this if you're sure you really need to, because it's
976usually a lot slower than using Python lists.
977
978
979How do I create a multidimensional list?
980----------------------------------------
981
982You probably tried to make a multidimensional array like this::
983
984 A = [[None] * 2] * 3
985
986This looks correct if you print it::
987
988 >>> A
989 [[None, None], [None, None], [None, None]]
990
991But when you assign a value, it shows up in multiple places:
992
993 >>> A[0][0] = 5
994 >>> A
995 [[5, None], [5, None], [5, None]]
996
997The reason is that replicating a list with ``*`` doesn't create copies, it only
998creates references to the existing objects. The ``*3`` creates a list
999containing 3 references to the same list of length two. Changes to one row will
1000show in all rows, which is almost certainly not what you want.
1001
1002The suggested approach is to create a list of the desired length first and then
1003fill in each element with a newly created list::
1004
1005 A = [None] * 3
1006 for i in range(3):
1007 A[i] = [None] * 2
1008
1009This generates a list containing 3 different lists of length two. You can also
1010use a list comprehension::
1011
1012 w, h = 2, 3
1013 A = [[None] * w for i in range(h)]
1014
1015Or, you can use an extension that provides a matrix datatype; `Numeric Python
Georg Brandl495f7b52009-10-27 15:28:25 +00001016<http://numpy.scipy.org/>`_ is the best known.
Georg Brandld7413152009-10-11 21:25:26 +00001017
1018
1019How do I apply a method to a sequence of objects?
1020-------------------------------------------------
1021
1022Use a list comprehension::
1023
Georg Brandl62eaaf62009-12-19 17:51:41 +00001024 result = [obj.method() for obj in mylist]
Georg Brandld7413152009-10-11 21:25:26 +00001025
1026
1027Dictionaries
1028============
1029
1030How can I get a dictionary to display its keys in a consistent order?
1031---------------------------------------------------------------------
1032
1033You can't. Dictionaries store their keys in an unpredictable order, so the
1034display order of a dictionary's elements will be similarly unpredictable.
1035
1036This can be frustrating if you want to save a printable version to a file, make
1037some changes and then compare it with some other printed dictionary. In this
1038case, use the ``pprint`` module to pretty-print the dictionary; the items will
1039be presented in order sorted by the key.
1040
Georg Brandl62eaaf62009-12-19 17:51:41 +00001041A more complicated solution is to subclass ``dict`` to create a
Georg Brandld7413152009-10-11 21:25:26 +00001042``SortedDict`` class that prints itself in a predictable order. Here's one
1043simpleminded implementation of such a class::
1044
Georg Brandl62eaaf62009-12-19 17:51:41 +00001045 class SortedDict(dict):
Georg Brandld7413152009-10-11 21:25:26 +00001046 def __repr__(self):
Georg Brandl62eaaf62009-12-19 17:51:41 +00001047 keys = sorted(self.keys())
1048 result = ("{!r}: {!r}".format(k, self[k]) for k in keys)
1049 return "{{{}}}".format(", ".join(result))
Georg Brandld7413152009-10-11 21:25:26 +00001050
Georg Brandl62eaaf62009-12-19 17:51:41 +00001051 __str__ = __repr__
Georg Brandld7413152009-10-11 21:25:26 +00001052
1053This will work for many common situations you might encounter, though it's far
1054from a perfect solution. The largest flaw is that if some values in the
1055dictionary are also dictionaries, their values won't be presented in any
1056particular order.
1057
1058
1059I want to do a complicated sort: can you do a Schwartzian Transform in Python?
1060------------------------------------------------------------------------------
1061
1062The technique, attributed to Randal Schwartz of the Perl community, sorts the
1063elements of a list by a metric which maps each element to its "sort value". In
1064Python, just use the ``key`` argument for the ``sort()`` method::
1065
1066 Isorted = L[:]
1067 Isorted.sort(key=lambda s: int(s[10:15]))
1068
1069The ``key`` argument is new in Python 2.4, for older versions this kind of
1070sorting is quite simple to do with list comprehensions. To sort a list of
1071strings by their uppercase values::
1072
Georg Brandl62eaaf62009-12-19 17:51:41 +00001073 tmp1 = [(x.upper(), x) for x in L] # Schwartzian transform
Georg Brandld7413152009-10-11 21:25:26 +00001074 tmp1.sort()
1075 Usorted = [x[1] for x in tmp1]
1076
1077To sort by the integer value of a subfield extending from positions 10-15 in
1078each string::
1079
Georg Brandl62eaaf62009-12-19 17:51:41 +00001080 tmp2 = [(int(s[10:15]), s) for s in L] # Schwartzian transform
Georg Brandld7413152009-10-11 21:25:26 +00001081 tmp2.sort()
1082 Isorted = [x[1] for x in tmp2]
1083
Georg Brandl62eaaf62009-12-19 17:51:41 +00001084For versions prior to 3.0, Isorted may also be computed by ::
Georg Brandld7413152009-10-11 21:25:26 +00001085
1086 def intfield(s):
1087 return int(s[10:15])
1088
1089 def Icmp(s1, s2):
1090 return cmp(intfield(s1), intfield(s2))
1091
1092 Isorted = L[:]
1093 Isorted.sort(Icmp)
1094
1095but since this method calls ``intfield()`` many times for each element of L, it
1096is slower than the Schwartzian Transform.
1097
1098
1099How can I sort one list by values from another list?
1100----------------------------------------------------
1101
Georg Brandl62eaaf62009-12-19 17:51:41 +00001102Merge them into an iterator of tuples, sort the resulting list, and then pick
Georg Brandld7413152009-10-11 21:25:26 +00001103out the element you want. ::
1104
1105 >>> list1 = ["what", "I'm", "sorting", "by"]
1106 >>> list2 = ["something", "else", "to", "sort"]
1107 >>> pairs = zip(list1, list2)
Georg Brandl62eaaf62009-12-19 17:51:41 +00001108 >>> pairs = sorted(pairs)
Georg Brandld7413152009-10-11 21:25:26 +00001109 >>> pairs
Georg Brandl62eaaf62009-12-19 17:51:41 +00001110 [("I'm", 'else'), ('by', 'sort'), ('sorting', 'to'), ('what', 'something')]
1111 >>> result = [x[1] for x in pairs]
Georg Brandld7413152009-10-11 21:25:26 +00001112 >>> result
1113 ['else', 'sort', 'to', 'something']
1114
Georg Brandl62eaaf62009-12-19 17:51:41 +00001115
Georg Brandld7413152009-10-11 21:25:26 +00001116An alternative for the last step is::
1117
Georg Brandl62eaaf62009-12-19 17:51:41 +00001118 >>> result = []
1119 >>> for p in pairs: result.append(p[1])
Georg Brandld7413152009-10-11 21:25:26 +00001120
1121If you find this more legible, you might prefer to use this instead of the final
1122list comprehension. However, it is almost twice as slow for long lists. Why?
1123First, the ``append()`` operation has to reallocate memory, and while it uses
1124some tricks to avoid doing that each time, it still has to do it occasionally,
1125and that costs quite a bit. Second, the expression "result.append" requires an
1126extra attribute lookup, and third, there's a speed reduction from having to make
1127all those function calls.
1128
1129
1130Objects
1131=======
1132
1133What is a class?
1134----------------
1135
1136A class is the particular object type created by executing a class statement.
1137Class objects are used as templates to create instance objects, which embody
1138both the data (attributes) and code (methods) specific to a datatype.
1139
1140A class can be based on one or more other classes, called its base class(es). It
1141then inherits the attributes and methods of its base classes. This allows an
1142object model to be successively refined by inheritance. You might have a
1143generic ``Mailbox`` class that provides basic accessor methods for a mailbox,
1144and subclasses such as ``MboxMailbox``, ``MaildirMailbox``, ``OutlookMailbox``
1145that handle various specific mailbox formats.
1146
1147
1148What is a method?
1149-----------------
1150
1151A method is a function on some object ``x`` that you normally call as
1152``x.name(arguments...)``. Methods are defined as functions inside the class
1153definition::
1154
1155 class C:
1156 def meth (self, arg):
1157 return arg * 2 + self.attribute
1158
1159
1160What is self?
1161-------------
1162
1163Self is merely a conventional name for the first argument of a method. A method
1164defined as ``meth(self, a, b, c)`` should be called as ``x.meth(a, b, c)`` for
1165some instance ``x`` of the class in which the definition occurs; the called
1166method will think it is called as ``meth(x, a, b, c)``.
1167
1168See also :ref:`why-self`.
1169
1170
1171How do I check if an object is an instance of a given class or of a subclass of it?
1172-----------------------------------------------------------------------------------
1173
1174Use the built-in function ``isinstance(obj, cls)``. You can check if an object
1175is an instance of any of a number of classes by providing a tuple instead of a
1176single class, e.g. ``isinstance(obj, (class1, class2, ...))``, and can also
1177check whether an object is one of Python's built-in types, e.g.
Georg Brandl62eaaf62009-12-19 17:51:41 +00001178``isinstance(obj, str)`` or ``isinstance(obj, (int, float, complex))``.
Georg Brandld7413152009-10-11 21:25:26 +00001179
1180Note that most programs do not use :func:`isinstance` on user-defined classes
1181very often. If you are developing the classes yourself, a more proper
1182object-oriented style is to define methods on the classes that encapsulate a
1183particular behaviour, instead of checking the object's class and doing a
1184different thing based on what class it is. For example, if you have a function
1185that does something::
1186
Georg Brandl62eaaf62009-12-19 17:51:41 +00001187 def search(obj):
Georg Brandld7413152009-10-11 21:25:26 +00001188 if isinstance(obj, Mailbox):
1189 # ... code to search a mailbox
1190 elif isinstance(obj, Document):
1191 # ... code to search a document
1192 elif ...
1193
1194A better approach is to define a ``search()`` method on all the classes and just
1195call it::
1196
1197 class Mailbox:
1198 def search(self):
1199 # ... code to search a mailbox
1200
1201 class Document:
1202 def search(self):
1203 # ... code to search a document
1204
1205 obj.search()
1206
1207
1208What is delegation?
1209-------------------
1210
1211Delegation is an object oriented technique (also called a design pattern).
1212Let's say you have an object ``x`` and want to change the behaviour of just one
1213of its methods. You can create a new class that provides a new implementation
1214of the method you're interested in changing and delegates all other methods to
1215the corresponding method of ``x``.
1216
1217Python programmers can easily implement delegation. For example, the following
1218class implements a class that behaves like a file but converts all written data
1219to uppercase::
1220
1221 class UpperOut:
1222
1223 def __init__(self, outfile):
1224 self._outfile = outfile
1225
1226 def write(self, s):
1227 self._outfile.write(s.upper())
1228
1229 def __getattr__(self, name):
1230 return getattr(self._outfile, name)
1231
1232Here the ``UpperOut`` class redefines the ``write()`` method to convert the
1233argument string to uppercase before calling the underlying
1234``self.__outfile.write()`` method. All other methods are delegated to the
1235underlying ``self.__outfile`` object. The delegation is accomplished via the
1236``__getattr__`` method; consult :ref:`the language reference <attribute-access>`
1237for more information about controlling attribute access.
1238
1239Note that for more general cases delegation can get trickier. When attributes
1240must be set as well as retrieved, the class must define a :meth:`__setattr__`
1241method too, and it must do so carefully. The basic implementation of
1242:meth:`__setattr__` is roughly equivalent to the following::
1243
1244 class X:
1245 ...
1246 def __setattr__(self, name, value):
1247 self.__dict__[name] = value
1248 ...
1249
1250Most :meth:`__setattr__` implementations must modify ``self.__dict__`` to store
1251local state for self without causing an infinite recursion.
1252
1253
1254How do I call a method defined in a base class from a derived class that overrides it?
1255--------------------------------------------------------------------------------------
1256
Georg Brandl62eaaf62009-12-19 17:51:41 +00001257Use the built-in :func:`super` function::
Georg Brandld7413152009-10-11 21:25:26 +00001258
1259 class Derived(Base):
1260 def meth (self):
1261 super(Derived, self).meth()
1262
Georg Brandl62eaaf62009-12-19 17:51:41 +00001263For version prior to 3.0, you may be using classic classes: For a class
1264definition such as ``class Derived(Base): ...`` you can call method ``meth()``
1265defined in ``Base`` (or one of ``Base``'s base classes) as ``Base.meth(self,
1266arguments...)``. Here, ``Base.meth`` is an unbound method, so you need to
1267provide the ``self`` argument.
Georg Brandld7413152009-10-11 21:25:26 +00001268
1269
1270How can I organize my code to make it easier to change the base class?
1271----------------------------------------------------------------------
1272
1273You could define an alias for the base class, assign the real base class to it
1274before your class definition, and use the alias throughout your class. Then all
1275you have to change is the value assigned to the alias. Incidentally, this trick
1276is also handy if you want to decide dynamically (e.g. depending on availability
1277of resources) which base class to use. Example::
1278
1279 BaseAlias = <real base class>
1280
1281 class Derived(BaseAlias):
1282 def meth(self):
1283 BaseAlias.meth(self)
1284 ...
1285
1286
1287How do I create static class data and static class methods?
1288-----------------------------------------------------------
1289
Georg Brandl62eaaf62009-12-19 17:51:41 +00001290Both static data and static methods (in the sense of C++ or Java) are supported
1291in Python.
Georg Brandld7413152009-10-11 21:25:26 +00001292
1293For static data, simply define a class attribute. To assign a new value to the
1294attribute, you have to explicitly use the class name in the assignment::
1295
1296 class C:
1297 count = 0 # number of times C.__init__ called
1298
1299 def __init__(self):
1300 C.count = C.count + 1
1301
1302 def getcount(self):
1303 return C.count # or return self.count
1304
1305``c.count`` also refers to ``C.count`` for any ``c`` such that ``isinstance(c,
1306C)`` holds, unless overridden by ``c`` itself or by some class on the base-class
1307search path from ``c.__class__`` back to ``C``.
1308
1309Caution: within a method of C, an assignment like ``self.count = 42`` creates a
Georg Brandl62eaaf62009-12-19 17:51:41 +00001310new and unrelated instance named "count" in ``self``'s own dict. Rebinding of a
1311class-static data name must always specify the class whether inside a method or
1312not::
Georg Brandld7413152009-10-11 21:25:26 +00001313
1314 C.count = 314
1315
Antoine Pitrouf3520402011-12-03 22:19:55 +01001316Static methods are possible::
Georg Brandld7413152009-10-11 21:25:26 +00001317
1318 class C:
1319 @staticmethod
1320 def static(arg1, arg2, arg3):
1321 # No 'self' parameter!
1322 ...
1323
1324However, a far more straightforward way to get the effect of a static method is
1325via a simple module-level function::
1326
1327 def getcount():
1328 return C.count
1329
1330If your code is structured so as to define one class (or tightly related class
1331hierarchy) per module, this supplies the desired encapsulation.
1332
1333
1334How can I overload constructors (or methods) in Python?
1335-------------------------------------------------------
1336
1337This answer actually applies to all methods, but the question usually comes up
1338first in the context of constructors.
1339
1340In C++ you'd write
1341
1342.. code-block:: c
1343
1344 class C {
1345 C() { cout << "No arguments\n"; }
1346 C(int i) { cout << "Argument is " << i << "\n"; }
1347 }
1348
1349In Python you have to write a single constructor that catches all cases using
1350default arguments. For example::
1351
1352 class C:
1353 def __init__(self, i=None):
1354 if i is None:
Georg Brandl62eaaf62009-12-19 17:51:41 +00001355 print("No arguments")
Georg Brandld7413152009-10-11 21:25:26 +00001356 else:
Georg Brandl62eaaf62009-12-19 17:51:41 +00001357 print("Argument is", i)
Georg Brandld7413152009-10-11 21:25:26 +00001358
1359This is not entirely equivalent, but close enough in practice.
1360
1361You could also try a variable-length argument list, e.g. ::
1362
1363 def __init__(self, *args):
1364 ...
1365
1366The same approach works for all method definitions.
1367
1368
1369I try to use __spam and I get an error about _SomeClassName__spam.
1370------------------------------------------------------------------
1371
1372Variable names with double leading underscores are "mangled" to provide a simple
1373but effective way to define class private variables. Any identifier of the form
1374``__spam`` (at least two leading underscores, at most one trailing underscore)
1375is textually replaced with ``_classname__spam``, where ``classname`` is the
1376current class name with any leading underscores stripped.
1377
1378This doesn't guarantee privacy: an outside user can still deliberately access
1379the "_classname__spam" attribute, and private values are visible in the object's
1380``__dict__``. Many Python programmers never bother to use private variable
1381names at all.
1382
1383
1384My class defines __del__ but it is not called when I delete the object.
1385-----------------------------------------------------------------------
1386
1387There are several possible reasons for this.
1388
1389The del statement does not necessarily call :meth:`__del__` -- it simply
1390decrements the object's reference count, and if this reaches zero
1391:meth:`__del__` is called.
1392
1393If your data structures contain circular links (e.g. a tree where each child has
1394a parent reference and each parent has a list of children) the reference counts
1395will never go back to zero. Once in a while Python runs an algorithm to detect
1396such cycles, but the garbage collector might run some time after the last
1397reference to your data structure vanishes, so your :meth:`__del__` method may be
1398called at an inconvenient and random time. This is inconvenient if you're trying
1399to reproduce a problem. Worse, the order in which object's :meth:`__del__`
1400methods are executed is arbitrary. You can run :func:`gc.collect` to force a
1401collection, but there *are* pathological cases where objects will never be
1402collected.
1403
1404Despite the cycle collector, it's still a good idea to define an explicit
1405``close()`` method on objects to be called whenever you're done with them. The
1406``close()`` method can then remove attributes that refer to subobjecs. Don't
1407call :meth:`__del__` directly -- :meth:`__del__` should call ``close()`` and
1408``close()`` should make sure that it can be called more than once for the same
1409object.
1410
1411Another way to avoid cyclical references is to use the :mod:`weakref` module,
1412which allows you to point to objects without incrementing their reference count.
1413Tree data structures, for instance, should use weak references for their parent
1414and sibling references (if they need them!).
1415
Georg Brandl62eaaf62009-12-19 17:51:41 +00001416.. XXX relevant for Python 3?
1417
1418 If the object has ever been a local variable in a function that caught an
1419 expression in an except clause, chances are that a reference to the object
1420 still exists in that function's stack frame as contained in the stack trace.
1421 Normally, calling :func:`sys.exc_clear` will take care of this by clearing
1422 the last recorded exception.
Georg Brandld7413152009-10-11 21:25:26 +00001423
1424Finally, if your :meth:`__del__` method raises an exception, a warning message
1425is printed to :data:`sys.stderr`.
1426
1427
1428How do I get a list of all instances of a given class?
1429------------------------------------------------------
1430
1431Python does not keep track of all instances of a class (or of a built-in type).
1432You can program the class's constructor to keep track of all instances by
1433keeping a list of weak references to each instance.
1434
1435
1436Modules
1437=======
1438
1439How do I create a .pyc file?
1440----------------------------
1441
1442When a module is imported for the first time (or when the source is more recent
1443than the current compiled file) a ``.pyc`` file containing the compiled code
1444should be created in the same directory as the ``.py`` file.
1445
1446One reason that a ``.pyc`` file may not be created is permissions problems with
1447the directory. This can happen, for example, if you develop as one user but run
1448as another, such as if you are testing with a web server. Creation of a .pyc
1449file is automatic if you're importing a module and Python has the ability
1450(permissions, free space, etc...) to write the compiled module back to the
1451directory.
1452
1453Running Python on a top level script is not considered an import and no ``.pyc``
1454will be created. For example, if you have a top-level module ``abc.py`` that
1455imports another module ``xyz.py``, when you run abc, ``xyz.pyc`` will be created
1456since xyz is imported, but no ``abc.pyc`` file will be created since ``abc.py``
1457isn't being imported.
1458
1459If you need to create abc.pyc -- that is, to create a .pyc file for a module
1460that is not imported -- you can, using the :mod:`py_compile` and
1461:mod:`compileall` modules.
1462
1463The :mod:`py_compile` module can manually compile any module. One way is to use
1464the ``compile()`` function in that module interactively::
1465
1466 >>> import py_compile
1467 >>> py_compile.compile('abc.py')
1468
1469This will write the ``.pyc`` to the same location as ``abc.py`` (or you can
1470override that with the optional parameter ``cfile``).
1471
1472You can also automatically compile all files in a directory or directories using
1473the :mod:`compileall` module. You can do it from the shell prompt by running
1474``compileall.py`` and providing the path of a directory containing Python files
1475to compile::
1476
1477 python -m compileall .
1478
1479
1480How do I find the current module name?
1481--------------------------------------
1482
1483A module can find out its own module name by looking at the predefined global
1484variable ``__name__``. If this has the value ``'__main__'``, the program is
1485running as a script. Many modules that are usually used by importing them also
1486provide a command-line interface or a self-test, and only execute this code
1487after checking ``__name__``::
1488
1489 def main():
Georg Brandl62eaaf62009-12-19 17:51:41 +00001490 print('Running test...')
Georg Brandld7413152009-10-11 21:25:26 +00001491 ...
1492
1493 if __name__ == '__main__':
1494 main()
1495
1496
1497How can I have modules that mutually import each other?
1498-------------------------------------------------------
1499
1500Suppose you have the following modules:
1501
1502foo.py::
1503
1504 from bar import bar_var
1505 foo_var = 1
1506
1507bar.py::
1508
1509 from foo import foo_var
1510 bar_var = 2
1511
1512The problem is that the interpreter will perform the following steps:
1513
1514* main imports foo
1515* Empty globals for foo are created
1516* foo is compiled and starts executing
1517* foo imports bar
1518* Empty globals for bar are created
1519* bar is compiled and starts executing
1520* bar imports foo (which is a no-op since there already is a module named foo)
1521* bar.foo_var = foo.foo_var
1522
1523The last step fails, because Python isn't done with interpreting ``foo`` yet and
1524the global symbol dictionary for ``foo`` is still empty.
1525
1526The same thing happens when you use ``import foo``, and then try to access
1527``foo.foo_var`` in global code.
1528
1529There are (at least) three possible workarounds for this problem.
1530
1531Guido van Rossum recommends avoiding all uses of ``from <module> import ...``,
1532and placing all code inside functions. Initializations of global variables and
1533class variables should use constants or built-in functions only. This means
1534everything from an imported module is referenced as ``<module>.<name>``.
1535
1536Jim Roskind suggests performing steps in the following order in each module:
1537
1538* exports (globals, functions, and classes that don't need imported base
1539 classes)
1540* ``import`` statements
1541* active code (including globals that are initialized from imported values).
1542
1543van Rossum doesn't like this approach much because the imports appear in a
1544strange place, but it does work.
1545
1546Matthias Urlichs recommends restructuring your code so that the recursive import
1547is not necessary in the first place.
1548
1549These solutions are not mutually exclusive.
1550
1551
1552__import__('x.y.z') returns <module 'x'>; how do I get z?
1553---------------------------------------------------------
1554
1555Try::
1556
1557 __import__('x.y.z').y.z
1558
1559For more realistic situations, you may have to do something like ::
1560
1561 m = __import__(s)
1562 for i in s.split(".")[1:]:
1563 m = getattr(m, i)
1564
1565See :mod:`importlib` for a convenience function called
1566:func:`~importlib.import_module`.
1567
1568
1569
1570When I edit an imported module and reimport it, the changes don't show up. Why does this happen?
1571-------------------------------------------------------------------------------------------------
1572
1573For reasons of efficiency as well as consistency, Python only reads the module
1574file on the first time a module is imported. If it didn't, in a program
1575consisting of many modules where each one imports the same basic module, the
1576basic module would be parsed and re-parsed many times. To force rereading of a
1577changed module, do this::
1578
Georg Brandl62eaaf62009-12-19 17:51:41 +00001579 import imp
Georg Brandld7413152009-10-11 21:25:26 +00001580 import modname
Georg Brandl62eaaf62009-12-19 17:51:41 +00001581 imp.reload(modname)
Georg Brandld7413152009-10-11 21:25:26 +00001582
1583Warning: this technique is not 100% fool-proof. In particular, modules
1584containing statements like ::
1585
1586 from modname import some_objects
1587
1588will continue to work with the old version of the imported objects. If the
1589module contains class definitions, existing class instances will *not* be
1590updated to use the new class definition. This can result in the following
1591paradoxical behaviour:
1592
Georg Brandl62eaaf62009-12-19 17:51:41 +00001593 >>> import imp
Georg Brandld7413152009-10-11 21:25:26 +00001594 >>> import cls
1595 >>> c = cls.C() # Create an instance of C
Georg Brandl62eaaf62009-12-19 17:51:41 +00001596 >>> imp.reload(cls)
1597 <module 'cls' from 'cls.py'>
Georg Brandld7413152009-10-11 21:25:26 +00001598 >>> isinstance(c, cls.C) # isinstance is false?!?
1599 False
1600
Georg Brandl62eaaf62009-12-19 17:51:41 +00001601The nature of the problem is made clear if you print out the "identity" of the
1602class objects:
Georg Brandld7413152009-10-11 21:25:26 +00001603
Georg Brandl62eaaf62009-12-19 17:51:41 +00001604 >>> hex(id(c.__class__))
1605 '0x7352a0'
1606 >>> hex(id(cls.C))
1607 '0x4198d0'