blob: 3c9e5f4d85c55e957d5a40374a4473d8a6d77c0c [file] [log] [blame]
Georg Brandld7413152009-10-11 21:25:26 +00001:tocdepth: 2
2
3===============
4Programming FAQ
5===============
6
7.. contents::
8
9General Questions
10=================
11
12Is there a source code level debugger with breakpoints, single-stepping, etc.?
13------------------------------------------------------------------------------
14
15Yes.
16
17The pdb module is a simple but adequate console-mode debugger for Python. It is
18part of the standard Python library, and is :mod:`documented in the Library
19Reference Manual <pdb>`. You can also write your own debugger by using the code
20for pdb as an example.
21
22The IDLE interactive development environment, which is part of the standard
23Python distribution (normally available as Tools/scripts/idle), includes a
24graphical debugger. There is documentation for the IDLE debugger at
25http://www.python.org/idle/doc/idle2.html#Debugger.
26
27PythonWin is a Python IDE that includes a GUI debugger based on pdb. The
28Pythonwin debugger colors breakpoints and has quite a few cool features such as
29debugging non-Pythonwin programs. Pythonwin is available as part of the `Python
30for Windows Extensions <http://sourceforge.net/projects/pywin32/>`__ project and
31as a part of the ActivePython distribution (see
32http://www.activestate.com/Products/ActivePython/index.html).
33
34`Boa Constructor <http://boa-constructor.sourceforge.net/>`_ is an IDE and GUI
35builder that uses wxWidgets. It offers visual frame creation and manipulation,
36an object inspector, many views on the source like object browsers, inheritance
37hierarchies, doc string generated html documentation, an advanced debugger,
38integrated help, and Zope support.
39
40`Eric <http://www.die-offenbachs.de/eric/index.html>`_ is an IDE built on PyQt
41and the Scintilla editing component.
42
43Pydb is a version of the standard Python debugger pdb, modified for use with DDD
44(Data Display Debugger), a popular graphical debugger front end. Pydb can be
45found at http://bashdb.sourceforge.net/pydb/ and DDD can be found at
46http://www.gnu.org/software/ddd.
47
48There are a number of commercial Python IDEs that include graphical debuggers.
49They include:
50
51* Wing IDE (http://wingware.com/)
52* Komodo IDE (http://www.activestate.com/Products/Komodo)
53
54
55Is there a tool to help find bugs or perform static analysis?
56-------------------------------------------------------------
57
58Yes.
59
60PyChecker is a static analysis tool that finds bugs in Python source code and
61warns about code complexity and style. You can get PyChecker from
62http://pychecker.sf.net.
63
64`Pylint <http://www.logilab.org/projects/pylint>`_ is another tool that checks
65if a module satisfies a coding standard, and also makes it possible to write
66plug-ins to add a custom feature. In addition to the bug checking that
67PyChecker performs, Pylint offers some additional features such as checking line
68length, whether variable names are well-formed according to your coding
69standard, whether declared interfaces are fully implemented, and more.
Georg Brandl495f7b52009-10-27 15:28:25 +000070http://www.logilab.org/card/pylint_manual provides a full list of Pylint's
71features.
Georg Brandld7413152009-10-11 21:25:26 +000072
73
74How can I create a stand-alone binary from a Python script?
75-----------------------------------------------------------
76
77You don't need the ability to compile Python to C code if all you want is a
78stand-alone program that users can download and run without having to install
79the Python distribution first. There are a number of tools that determine the
80set of modules required by a program and bind these modules together with a
81Python binary to produce a single executable.
82
83One is to use the freeze tool, which is included in the Python source tree as
84``Tools/freeze``. It converts Python byte code to C arrays; a C compiler you can
85embed all your modules into a new program, which is then linked with the
86standard Python modules.
87
88It works by scanning your source recursively for import statements (in both
89forms) and looking for the modules in the standard Python path as well as in the
90source directory (for built-in modules). It then turns the bytecode for modules
91written in Python into C code (array initializers that can be turned into code
92objects using the marshal module) and creates a custom-made config file that
93only contains those built-in modules which are actually used in the program. It
94then compiles the generated C code and links it with the rest of the Python
95interpreter to form a self-contained binary which acts exactly like your script.
96
97Obviously, freeze requires a C compiler. There are several other utilities
98which don't. One is Thomas Heller's py2exe (Windows only) at
99
100 http://www.py2exe.org/
101
102Another is Christian Tismer's `SQFREEZE <http://starship.python.net/crew/pirx>`_
103which appends the byte code to a specially-prepared Python interpreter that can
104find the byte code in the executable.
105
106Other tools include Fredrik Lundh's `Squeeze
107<http://www.pythonware.com/products/python/squeeze>`_ and Anthony Tuininga's
108`cx_Freeze <http://starship.python.net/crew/atuining/cx_Freeze/index.html>`_.
109
110
111Are there coding standards or a style guide for Python programs?
112----------------------------------------------------------------
113
114Yes. The coding style required for standard library modules is documented as
115:pep:`8`.
116
117
118My program is too slow. How do I speed it up?
119---------------------------------------------
120
121That's a tough one, in general. There are many tricks to speed up Python code;
122consider rewriting parts in C as a last resort.
123
124In some cases it's possible to automatically translate Python to C or x86
125assembly language, meaning that you don't have to modify your code to gain
126increased speed.
127
128.. XXX seems to have overlap with other questions!
129
130`Pyrex <http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/>`_ can compile a
131slightly modified version of Python code into a C extension, and can be used on
132many different platforms.
133
134`Psyco <http://psyco.sourceforge.net>`_ is a just-in-time compiler that
135translates Python code into x86 assembly language. If you can use it, Psyco can
136provide dramatic speedups for critical functions.
137
138The rest of this answer will discuss various tricks for squeezing a bit more
139speed out of Python code. *Never* apply any optimization tricks unless you know
140you need them, after profiling has indicated that a particular function is the
141heavily executed hot spot in the code. Optimizations almost always make the
142code less clear, and you shouldn't pay the costs of reduced clarity (increased
143development time, greater likelihood of bugs) unless the resulting performance
144benefit is worth it.
145
146There is a page on the wiki devoted to `performance tips
147<http://wiki.python.org/moin/PythonSpeed/PerformanceTips>`_.
148
149Guido van Rossum has written up an anecdote related to optimization at
150http://www.python.org/doc/essays/list2str.html.
151
152One thing to notice is that function and (especially) method calls are rather
153expensive; if you have designed a purely OO interface with lots of tiny
154functions that don't do much more than get or set an instance variable or call
155another method, you might consider using a more direct way such as directly
156accessing instance variables. Also see the standard module :mod:`profile` which
157makes it possible to find out where your program is spending most of its time
158(if you have some patience -- the profiling itself can slow your program down by
159an order of magnitude).
160
161Remember that many standard optimization heuristics you may know from other
162programming experience may well apply to Python. For example it may be faster
163to send output to output devices using larger writes rather than smaller ones in
164order to reduce the overhead of kernel system calls. Thus CGI scripts that
165write all output in "one shot" may be faster than those that write lots of small
166pieces of output.
167
168Also, be sure to use Python's core features where appropriate. For example,
169slicing allows programs to chop up lists and other sequence objects in a single
170tick of the interpreter's mainloop using highly optimized C implementations.
171Thus to get the same effect as::
172
173 L2 = []
174 for i in range[3]:
175 L2.append(L1[i])
176
177it is much shorter and far faster to use ::
178
Georg Brandl62eaaf62009-12-19 17:51:41 +0000179 L2 = list(L1[:3]) # "list" is redundant if L1 is a list.
Georg Brandld7413152009-10-11 21:25:26 +0000180
181Note that the functionally-oriented builtins such as :func:`map`, :func:`zip`,
182and friends can be a convenient accelerator for loops that perform a single
183task. For example to pair the elements of two lists together::
184
Georg Brandl11b63622009-12-20 14:21:27 +0000185 >>> list(zip([1, 2, 3], [4, 5, 6]))
Georg Brandld7413152009-10-11 21:25:26 +0000186 [(1, 4), (2, 5), (3, 6)]
187
188or to compute a number of sines::
189
Georg Brandl62eaaf62009-12-19 17:51:41 +0000190 >>> list(map(math.sin, (1, 2, 3, 4)))
191 [0.841470984808, 0.909297426826, 0.14112000806, -0.756802495308]
Georg Brandld7413152009-10-11 21:25:26 +0000192
193The operation completes very quickly in such cases.
194
Georg Brandl11b63622009-12-20 14:21:27 +0000195Other examples include the ``join()`` and ``split()`` :ref:`methods
196of string objects <string-methods>`.
197
Georg Brandld7413152009-10-11 21:25:26 +0000198For example if s1..s7 are large (10K+) strings then
199``"".join([s1,s2,s3,s4,s5,s6,s7])`` may be far faster than the more obvious
200``s1+s2+s3+s4+s5+s6+s7``, since the "summation" will compute many
201subexpressions, whereas ``join()`` does all the copying in one pass. For
Georg Brandl11b63622009-12-20 14:21:27 +0000202manipulating strings, use the ``replace()`` and the ``format()`` :ref:`methods
203on string objects <string-methods>`. Use regular expressions only when you're
204not dealing with constant string patterns.
Georg Brandld7413152009-10-11 21:25:26 +0000205
206Be sure to use the :meth:`list.sort` builtin method to do sorting, and see the
207`sorting mini-HOWTO <http://wiki.python.org/moin/HowTo/Sorting>`_ for examples
208of moderately advanced usage. :meth:`list.sort` beats other techniques for
209sorting in all but the most extreme circumstances.
210
211Another common trick is to "push loops into functions or methods." For example
212suppose you have a program that runs slowly and you use the profiler to
213determine that a Python function ``ff()`` is being called lots of times. If you
Georg Brandl62eaaf62009-12-19 17:51:41 +0000214notice that ``ff()``::
Georg Brandld7413152009-10-11 21:25:26 +0000215
216 def ff(x):
217 ... # do something with x computing result...
218 return result
219
220tends to be called in loops like::
221
222 list = map(ff, oldlist)
223
224or::
225
226 for x in sequence:
227 value = ff(x)
228 ... # do something with value...
229
230then you can often eliminate function call overhead by rewriting ``ff()`` to::
231
232 def ffseq(seq):
233 resultseq = []
234 for x in seq:
235 ... # do something with x computing result...
236 resultseq.append(result)
237 return resultseq
238
239and rewrite the two examples to ``list = ffseq(oldlist)`` and to::
240
241 for value in ffseq(sequence):
242 ... # do something with value...
243
244Single calls to ``ff(x)`` translate to ``ffseq([x])[0]`` with little penalty.
245Of course this technique is not always appropriate and there are other variants
246which you can figure out.
247
248You can gain some performance by explicitly storing the results of a function or
249method lookup into a local variable. A loop like::
250
251 for key in token:
252 dict[key] = dict.get(key, 0) + 1
253
254resolves ``dict.get`` every iteration. If the method isn't going to change, a
255slightly faster implementation is::
256
257 dict_get = dict.get # look up the method once
258 for key in token:
259 dict[key] = dict_get(key, 0) + 1
260
261Default arguments can be used to determine values once, at compile time instead
262of at run time. This can only be done for functions or objects which will not
263be changed during program execution, such as replacing ::
264
265 def degree_sin(deg):
266 return math.sin(deg * math.pi / 180.0)
267
268with ::
269
270 def degree_sin(deg, factor=math.pi/180.0, sin=math.sin):
271 return sin(deg * factor)
272
273Because this trick uses default arguments for terms which should not be changed,
274it should only be used when you are not concerned with presenting a possibly
275confusing API to your users.
276
277
278Core Language
279=============
280
R. David Murrayc04a6942009-11-14 22:21:32 +0000281Why am I getting an UnboundLocalError when the variable has a value?
282--------------------------------------------------------------------
Georg Brandld7413152009-10-11 21:25:26 +0000283
R. David Murrayc04a6942009-11-14 22:21:32 +0000284It can be a surprise to get the UnboundLocalError in previously working
285code when it is modified by adding an assignment statement somewhere in
286the body of a function.
Georg Brandld7413152009-10-11 21:25:26 +0000287
R. David Murrayc04a6942009-11-14 22:21:32 +0000288This code:
Georg Brandld7413152009-10-11 21:25:26 +0000289
R. David Murrayc04a6942009-11-14 22:21:32 +0000290 >>> x = 10
291 >>> def bar():
292 ... print(x)
293 >>> bar()
294 10
Georg Brandld7413152009-10-11 21:25:26 +0000295
R. David Murrayc04a6942009-11-14 22:21:32 +0000296works, but this code:
Georg Brandld7413152009-10-11 21:25:26 +0000297
R. David Murrayc04a6942009-11-14 22:21:32 +0000298 >>> x = 10
299 >>> def foo():
300 ... print(x)
301 ... x += 1
Georg Brandld7413152009-10-11 21:25:26 +0000302
R. David Murrayc04a6942009-11-14 22:21:32 +0000303results in an UnboundLocalError:
Georg Brandld7413152009-10-11 21:25:26 +0000304
R. David Murrayc04a6942009-11-14 22:21:32 +0000305 >>> foo()
306 Traceback (most recent call last):
307 ...
308 UnboundLocalError: local variable 'x' referenced before assignment
309
310This is because when you make an assignment to a variable in a scope, that
311variable becomes local to that scope and shadows any similarly named variable
312in the outer scope. Since the last statement in foo assigns a new value to
313``x``, the compiler recognizes it as a local variable. Consequently when the
R. David Murray18163c32009-11-14 22:27:22 +0000314earlier ``print(x)`` attempts to print the uninitialized local variable and
R. David Murrayc04a6942009-11-14 22:21:32 +0000315an error results.
316
317In the example above you can access the outer scope variable by declaring it
318global:
319
320 >>> x = 10
321 >>> def foobar():
322 ... global x
323 ... print(x)
324 ... x += 1
325 >>> foobar()
326 10
327
328This explicit declaration is required in order to remind you that (unlike the
329superficially analogous situation with class and instance variables) you are
330actually modifying the value of the variable in the outer scope:
331
332 >>> print(x)
333 11
334
335You can do a similar thing in a nested scope using the :keyword:`nonlocal`
336keyword:
337
338 >>> def foo():
339 ... x = 10
340 ... def bar():
341 ... nonlocal x
342 ... print(x)
343 ... x += 1
344 ... bar()
345 ... print(x)
346 >>> foo()
347 10
348 11
Georg Brandld7413152009-10-11 21:25:26 +0000349
350
351What are the rules for local and global variables in Python?
352------------------------------------------------------------
353
354In Python, variables that are only referenced inside a function are implicitly
355global. If a variable is assigned a new value anywhere within the function's
356body, it's assumed to be a local. If a variable is ever assigned a new value
357inside the function, the variable is implicitly local, and you need to
358explicitly declare it as 'global'.
359
360Though a bit surprising at first, a moment's consideration explains this. On
361one hand, requiring :keyword:`global` for assigned variables provides a bar
362against unintended side-effects. On the other hand, if ``global`` was required
363for all global references, you'd be using ``global`` all the time. You'd have
364to declare as global every reference to a builtin function or to a component of
365an imported module. This clutter would defeat the usefulness of the ``global``
366declaration for identifying side-effects.
367
368
369How do I share global variables across modules?
370------------------------------------------------
371
372The canonical way to share information across modules within a single program is
373to create a special module (often called config or cfg). Just import the config
374module in all modules of your application; the module then becomes available as
375a global name. Because there is only one instance of each module, any changes
376made to the module object get reflected everywhere. For example:
377
378config.py::
379
380 x = 0 # Default value of the 'x' configuration setting
381
382mod.py::
383
384 import config
385 config.x = 1
386
387main.py::
388
389 import config
390 import mod
Georg Brandl62eaaf62009-12-19 17:51:41 +0000391 print(config.x)
Georg Brandld7413152009-10-11 21:25:26 +0000392
393Note that using a module is also the basis for implementing the Singleton design
394pattern, for the same reason.
395
396
397What are the "best practices" for using import in a module?
398-----------------------------------------------------------
399
400In general, don't use ``from modulename import *``. Doing so clutters the
401importer's namespace. Some people avoid this idiom even with the few modules
402that were designed to be imported in this manner. Modules designed in this
Georg Brandld404fa62009-10-13 16:55:12 +0000403manner include :mod:`tkinter`, and :mod:`threading`.
Georg Brandld7413152009-10-11 21:25:26 +0000404
405Import modules at the top of a file. Doing so makes it clear what other modules
406your code requires and avoids questions of whether the module name is in scope.
407Using one import per line makes it easy to add and delete module imports, but
408using multiple imports per line uses less screen space.
409
410It's good practice if you import modules in the following order:
411
Georg Brandl62eaaf62009-12-19 17:51:41 +00004121. standard library modules -- e.g. ``sys``, ``os``, ``getopt``, ``re``
Georg Brandld7413152009-10-11 21:25:26 +00004132. third-party library modules (anything installed in Python's site-packages
414 directory) -- e.g. mx.DateTime, ZODB, PIL.Image, etc.
4153. locally-developed modules
416
417Never use relative package imports. If you're writing code that's in the
418``package.sub.m1`` module and want to import ``package.sub.m2``, do not just
Georg Brandl11b63622009-12-20 14:21:27 +0000419write ``from . import m2``, even though it's legal. Write ``from package.sub
420import m2`` instead. See :pep:`328` for details.
Georg Brandld7413152009-10-11 21:25:26 +0000421
422It is sometimes necessary to move imports to a function or class to avoid
423problems with circular imports. Gordon McMillan says:
424
425 Circular imports are fine where both modules use the "import <module>" form
426 of import. They fail when the 2nd module wants to grab a name out of the
427 first ("from module import name") and the import is at the top level. That's
428 because names in the 1st are not yet available, because the first module is
429 busy importing the 2nd.
430
431In this case, if the second module is only used in one function, then the import
432can easily be moved into that function. By the time the import is called, the
433first module will have finished initializing, and the second module can do its
434import.
435
436It may also be necessary to move imports out of the top level of code if some of
437the modules are platform-specific. In that case, it may not even be possible to
438import all of the modules at the top of the file. In this case, importing the
439correct modules in the corresponding platform-specific code is a good option.
440
441Only move imports into a local scope, such as inside a function definition, if
442it's necessary to solve a problem such as avoiding a circular import or are
443trying to reduce the initialization time of a module. This technique is
444especially helpful if many of the imports are unnecessary depending on how the
445program executes. You may also want to move imports into a function if the
446modules are only ever used in that function. Note that loading a module the
447first time may be expensive because of the one time initialization of the
448module, but loading a module multiple times is virtually free, costing only a
449couple of dictionary lookups. Even if the module name has gone out of scope,
450the module is probably available in :data:`sys.modules`.
451
452If only instances of a specific class use a module, then it is reasonable to
453import the module in the class's ``__init__`` method and then assign the module
454to an instance variable so that the module is always available (via that
455instance variable) during the life of the object. Note that to delay an import
456until the class is instantiated, the import must be inside a method. Putting
457the import inside the class but outside of any method still causes the import to
458occur when the module is initialized.
459
460
461How can I pass optional or keyword parameters from one function to another?
462---------------------------------------------------------------------------
463
464Collect the arguments using the ``*`` and ``**`` specifiers in the function's
465parameter list; this gives you the positional arguments as a tuple and the
466keyword arguments as a dictionary. You can then pass these arguments when
467calling another function by using ``*`` and ``**``::
468
469 def f(x, *args, **kwargs):
470 ...
471 kwargs['width'] = '14.3c'
472 ...
473 g(x, *args, **kwargs)
474
475In the unlikely case that you care about Python versions older than 2.0, use
476:func:`apply`::
477
478 def f(x, *args, **kwargs):
479 ...
480 kwargs['width'] = '14.3c'
481 ...
482 apply(g, (x,)+args, kwargs)
483
484
485How do I write a function with output parameters (call by reference)?
486---------------------------------------------------------------------
487
488Remember that arguments are passed by assignment in Python. Since assignment
489just creates references to objects, there's no alias between an argument name in
490the caller and callee, and so no call-by-reference per se. You can achieve the
491desired effect in a number of ways.
492
4931) By returning a tuple of the results::
494
495 def func2(a, b):
496 a = 'new-value' # a and b are local names
497 b = b + 1 # assigned to new objects
498 return a, b # return new values
499
500 x, y = 'old-value', 99
501 x, y = func2(x, y)
Georg Brandl62eaaf62009-12-19 17:51:41 +0000502 print(x, y) # output: new-value 100
Georg Brandld7413152009-10-11 21:25:26 +0000503
504 This is almost always the clearest solution.
505
5062) By using global variables. This isn't thread-safe, and is not recommended.
507
5083) By passing a mutable (changeable in-place) object::
509
510 def func1(a):
511 a[0] = 'new-value' # 'a' references a mutable list
512 a[1] = a[1] + 1 # changes a shared object
513
514 args = ['old-value', 99]
515 func1(args)
Georg Brandl62eaaf62009-12-19 17:51:41 +0000516 print(args[0], args[1]) # output: new-value 100
Georg Brandld7413152009-10-11 21:25:26 +0000517
5184) By passing in a dictionary that gets mutated::
519
520 def func3(args):
521 args['a'] = 'new-value' # args is a mutable dictionary
522 args['b'] = args['b'] + 1 # change it in-place
523
524 args = {'a':' old-value', 'b': 99}
525 func3(args)
Georg Brandl62eaaf62009-12-19 17:51:41 +0000526 print(args['a'], args['b'])
Georg Brandld7413152009-10-11 21:25:26 +0000527
5285) Or bundle up values in a class instance::
529
530 class callByRef:
531 def __init__(self, **args):
532 for (key, value) in args.items():
533 setattr(self, key, value)
534
535 def func4(args):
536 args.a = 'new-value' # args is a mutable callByRef
537 args.b = args.b + 1 # change object in-place
538
539 args = callByRef(a='old-value', b=99)
540 func4(args)
Georg Brandl62eaaf62009-12-19 17:51:41 +0000541 print(args.a, args.b)
Georg Brandld7413152009-10-11 21:25:26 +0000542
543
544 There's almost never a good reason to get this complicated.
545
546Your best choice is to return a tuple containing the multiple results.
547
548
549How do you make a higher order function in Python?
550--------------------------------------------------
551
552You have two choices: you can use nested scopes or you can use callable objects.
553For example, suppose you wanted to define ``linear(a,b)`` which returns a
554function ``f(x)`` that computes the value ``a*x+b``. Using nested scopes::
555
556 def linear(a, b):
557 def result(x):
558 return a * x + b
559 return result
560
561Or using a callable object::
562
563 class linear:
564
565 def __init__(self, a, b):
566 self.a, self.b = a, b
567
568 def __call__(self, x):
569 return self.a * x + self.b
570
571In both cases, ::
572
573 taxes = linear(0.3, 2)
574
575gives a callable object where ``taxes(10e6) == 0.3 * 10e6 + 2``.
576
577The callable object approach has the disadvantage that it is a bit slower and
578results in slightly longer code. However, note that a collection of callables
579can share their signature via inheritance::
580
581 class exponential(linear):
582 # __init__ inherited
583 def __call__(self, x):
584 return self.a * (x ** self.b)
585
586Object can encapsulate state for several methods::
587
588 class counter:
589
590 value = 0
591
592 def set(self, x):
593 self.value = x
594
595 def up(self):
596 self.value = self.value + 1
597
598 def down(self):
599 self.value = self.value - 1
600
601 count = counter()
602 inc, dec, reset = count.up, count.down, count.set
603
604Here ``inc()``, ``dec()`` and ``reset()`` act like functions which share the
605same counting variable.
606
607
608How do I copy an object in Python?
609----------------------------------
610
611In general, try :func:`copy.copy` or :func:`copy.deepcopy` for the general case.
612Not all objects can be copied, but most can.
613
614Some objects can be copied more easily. Dictionaries have a :meth:`~dict.copy`
615method::
616
617 newdict = olddict.copy()
618
619Sequences can be copied by slicing::
620
621 new_l = l[:]
622
623
624How can I find the methods or attributes of an object?
625------------------------------------------------------
626
627For an instance x of a user-defined class, ``dir(x)`` returns an alphabetized
628list of the names containing the instance attributes and methods and attributes
629defined by its class.
630
631
632How can my code discover the name of an object?
633-----------------------------------------------
634
635Generally speaking, it can't, because objects don't really have names.
636Essentially, assignment always binds a name to a value; The same is true of
637``def`` and ``class`` statements, but in that case the value is a
638callable. Consider the following code::
639
640 class A:
641 pass
642
643 B = A
644
645 a = B()
646 b = a
Georg Brandl62eaaf62009-12-19 17:51:41 +0000647 print(b)
648 <__main__.A object at 0x16D07CC>
649 print(a)
650 <__main__.A object at 0x16D07CC>
Georg Brandld7413152009-10-11 21:25:26 +0000651
652Arguably the class has a name: even though it is bound to two names and invoked
653through the name B the created instance is still reported as an instance of
654class A. However, it is impossible to say whether the instance's name is a or
655b, since both names are bound to the same value.
656
657Generally speaking it should not be necessary for your code to "know the names"
658of particular values. Unless you are deliberately writing introspective
659programs, this is usually an indication that a change of approach might be
660beneficial.
661
662In comp.lang.python, Fredrik Lundh once gave an excellent analogy in answer to
663this question:
664
665 The same way as you get the name of that cat you found on your porch: the cat
666 (object) itself cannot tell you its name, and it doesn't really care -- so
667 the only way to find out what it's called is to ask all your neighbours
668 (namespaces) if it's their cat (object)...
669
670 ....and don't be surprised if you'll find that it's known by many names, or
671 no name at all!
672
673
674What's up with the comma operator's precedence?
675-----------------------------------------------
676
677Comma is not an operator in Python. Consider this session::
678
679 >>> "a" in "b", "a"
Georg Brandl62eaaf62009-12-19 17:51:41 +0000680 (False, 'a')
Georg Brandld7413152009-10-11 21:25:26 +0000681
682Since the comma is not an operator, but a separator between expressions the
683above is evaluated as if you had entered::
684
685 >>> ("a" in "b"), "a"
686
687not::
688
Georg Brandl62eaaf62009-12-19 17:51:41 +0000689 >>> "a" in ("b", "a")
Georg Brandld7413152009-10-11 21:25:26 +0000690
691The same is true of the various assignment operators (``=``, ``+=`` etc). They
692are not truly operators but syntactic delimiters in assignment statements.
693
694
695Is there an equivalent of C's "?:" ternary operator?
696----------------------------------------------------
697
698Yes, this feature was added in Python 2.5. The syntax would be as follows::
699
700 [on_true] if [expression] else [on_false]
701
702 x, y = 50, 25
703
704 small = x if x < y else y
705
706For versions previous to 2.5 the answer would be 'No'.
707
708.. XXX remove rest?
709
710In many cases you can mimic ``a ? b : c`` with ``a and b or c``, but there's a
711flaw: if *b* is zero (or empty, or ``None`` -- anything that tests false) then
712*c* will be selected instead. In many cases you can prove by looking at the
713code that this can't happen (e.g. because *b* is a constant or has a type that
714can never be false), but in general this can be a problem.
715
716Tim Peters (who wishes it was Steve Majewski) suggested the following solution:
717``(a and [b] or [c])[0]``. Because ``[b]`` is a singleton list it is never
718false, so the wrong path is never taken; then applying ``[0]`` to the whole
719thing gets the *b* or *c* that you really wanted. Ugly, but it gets you there
720in the rare cases where it is really inconvenient to rewrite your code using
721'if'.
722
723The best course is usually to write a simple ``if...else`` statement. Another
724solution is to implement the ``?:`` operator as a function::
725
726 def q(cond, on_true, on_false):
727 if cond:
728 if not isfunction(on_true):
729 return on_true
730 else:
Georg Brandl62eaaf62009-12-19 17:51:41 +0000731 return on_true()
Georg Brandld7413152009-10-11 21:25:26 +0000732 else:
733 if not isfunction(on_false):
734 return on_false
735 else:
Georg Brandl62eaaf62009-12-19 17:51:41 +0000736 return on_false()
Georg Brandld7413152009-10-11 21:25:26 +0000737
738In most cases you'll pass b and c directly: ``q(a, b, c)``. To avoid evaluating
739b or c when they shouldn't be, encapsulate them within a lambda function, e.g.:
740``q(a, lambda: b, lambda: c)``.
741
742It has been asked *why* Python has no if-then-else expression. There are
743several answers: many languages do just fine without one; it can easily lead to
744less readable code; no sufficiently "Pythonic" syntax has been discovered; a
745search of the standard library found remarkably few places where using an
746if-then-else expression would make the code more understandable.
747
748In 2002, :pep:`308` was written proposing several possible syntaxes and the
749community was asked to vote on the issue. The vote was inconclusive. Most
750people liked one of the syntaxes, but also hated other syntaxes; many votes
751implied that people preferred no ternary operator rather than having a syntax
752they hated.
753
754
755Is it possible to write obfuscated one-liners in Python?
756--------------------------------------------------------
757
758Yes. Usually this is done by nesting :keyword:`lambda` within
759:keyword:`lambda`. See the following three examples, due to Ulf Bartelt::
760
Georg Brandl62eaaf62009-12-19 17:51:41 +0000761 from functools import reduce
762
Georg Brandld7413152009-10-11 21:25:26 +0000763 # Primes < 1000
Georg Brandl62eaaf62009-12-19 17:51:41 +0000764 print(list(filter(None,map(lambda y:y*reduce(lambda x,y:x*y!=0,
765 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 +0000766
767 # First 10 Fibonacci numbers
Georg Brandl62eaaf62009-12-19 17:51:41 +0000768 print(list(map(lambda x,f=lambda x,f:(f(x-1,f)+f(x-2,f)) if x>1 else 1:
769 f(x,f), range(10))))
Georg Brandld7413152009-10-11 21:25:26 +0000770
771 # Mandelbrot set
Georg Brandl62eaaf62009-12-19 17:51:41 +0000772 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 +0000773 Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,Sy=Sy,L=lambda yc,Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,i=IM,
774 Sx=Sx,Sy=Sy:reduce(lambda x,y:x+y,map(lambda x,xc=Ru,yc=yc,Ru=Ru,Ro=Ro,
775 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
776 >=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(
777 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 +0000778 ))))(-2.1, 0.7, -1.2, 1.2, 30, 80, 24))
Georg Brandld7413152009-10-11 21:25:26 +0000779 # \___ ___/ \___ ___/ | | |__ lines on screen
780 # V V | |______ columns on screen
781 # | | |__________ maximum of "iterations"
782 # | |_________________ range on y axis
783 # |____________________________ range on x axis
784
785Don't try this at home, kids!
786
787
788Numbers and strings
789===================
790
791How do I specify hexadecimal and octal integers?
792------------------------------------------------
793
Georg Brandl62eaaf62009-12-19 17:51:41 +0000794To specify an octal digit, precede the octal value with a zero, and then a lower
795or uppercase "o". For example, to set the variable "a" to the octal value "10"
796(8 in decimal), type::
Georg Brandld7413152009-10-11 21:25:26 +0000797
Georg Brandl62eaaf62009-12-19 17:51:41 +0000798 >>> a = 0o10
Georg Brandld7413152009-10-11 21:25:26 +0000799 >>> a
800 8
801
802Hexadecimal is just as easy. Simply precede the hexadecimal number with a zero,
803and then a lower or uppercase "x". Hexadecimal digits can be specified in lower
804or uppercase. For example, in the Python interpreter::
805
806 >>> a = 0xa5
807 >>> a
808 165
809 >>> b = 0XB2
810 >>> b
811 178
812
813
Georg Brandl62eaaf62009-12-19 17:51:41 +0000814Why does -22 // 10 return -3?
815-----------------------------
Georg Brandld7413152009-10-11 21:25:26 +0000816
817It's primarily driven by the desire that ``i % j`` have the same sign as ``j``.
818If you want that, and also want::
819
Georg Brandl62eaaf62009-12-19 17:51:41 +0000820 i == (i // j) * j + (i % j)
Georg Brandld7413152009-10-11 21:25:26 +0000821
822then integer division has to return the floor. C also requires that identity to
Georg Brandl62eaaf62009-12-19 17:51:41 +0000823hold, and then compilers that truncate ``i // j`` need to make ``i % j`` have
824the same sign as ``i``.
Georg Brandld7413152009-10-11 21:25:26 +0000825
826There are few real use cases for ``i % j`` when ``j`` is negative. When ``j``
827is positive, there are many, and in virtually all of them it's more useful for
828``i % j`` to be ``>= 0``. If the clock says 10 now, what did it say 200 hours
829ago? ``-190 % 12 == 2`` is useful; ``-190 % 12 == -10`` is a bug waiting to
830bite.
831
832
833How do I convert a string to a number?
834--------------------------------------
835
836For integers, use the built-in :func:`int` type constructor, e.g. ``int('144')
837== 144``. Similarly, :func:`float` converts to floating-point,
838e.g. ``float('144') == 144.0``.
839
840By default, these interpret the number as decimal, so that ``int('0144') ==
841144`` and ``int('0x144')`` raises :exc:`ValueError`. ``int(string, base)`` takes
842the base to convert from as a second optional argument, so ``int('0x144', 16) ==
843324``. If the base is specified as 0, the number is interpreted using Python's
844rules: a leading '0' indicates octal, and '0x' indicates a hex number.
845
846Do not use the built-in function :func:`eval` if all you need is to convert
847strings to numbers. :func:`eval` will be significantly slower and it presents a
848security risk: someone could pass you a Python expression that might have
849unwanted side effects. For example, someone could pass
850``__import__('os').system("rm -rf $HOME")`` which would erase your home
851directory.
852
853:func:`eval` also has the effect of interpreting numbers as Python expressions,
Georg Brandl62eaaf62009-12-19 17:51:41 +0000854so that e.g. ``eval('09')`` gives a syntax error because Python does not allow
855leading '0' in a decimal number (except '0').
Georg Brandld7413152009-10-11 21:25:26 +0000856
857
858How do I convert a number to a string?
859--------------------------------------
860
861To convert, e.g., the number 144 to the string '144', use the built-in type
862constructor :func:`str`. If you want a hexadecimal or octal representation, use
Georg Brandl62eaaf62009-12-19 17:51:41 +0000863the built-in functions :func:`hex` or :func:`oct`. For fancy formatting, see
864the :ref:`string-formatting` section, e.g. ``"{:04d}".format(144)`` yields
Georg Brandl11b63622009-12-20 14:21:27 +0000865``'0144'`` and ``"{:.3f}".format(1/3)`` yields ``'0.333'``.
Georg Brandld7413152009-10-11 21:25:26 +0000866
867
868How do I modify a string in place?
869----------------------------------
870
871You can't, because strings are immutable. If you need an object with this
872ability, try converting the string to a list or use the array module::
873
874 >>> s = "Hello, world"
875 >>> a = list(s)
Georg Brandl62eaaf62009-12-19 17:51:41 +0000876 >>> print(a)
Georg Brandld7413152009-10-11 21:25:26 +0000877 ['H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd']
878 >>> a[7:] = list("there!")
879 >>> ''.join(a)
880 'Hello, there!'
881
882 >>> import array
Georg Brandl62eaaf62009-12-19 17:51:41 +0000883 >>> a = array.array('u', s)
884 >>> print(a)
885 array('u', 'Hello, world')
886 >>> a[0] = 'y'
887 >>> print(a)
888 array('u', 'yello world')
889 >>> a.tounicode()
Georg Brandld7413152009-10-11 21:25:26 +0000890 'yello, world'
891
892
893How do I use strings to call functions/methods?
894-----------------------------------------------
895
896There are various techniques.
897
898* The best is to use a dictionary that maps strings to functions. The primary
899 advantage of this technique is that the strings do not need to match the names
900 of the functions. This is also the primary technique used to emulate a case
901 construct::
902
903 def a():
904 pass
905
906 def b():
907 pass
908
909 dispatch = {'go': a, 'stop': b} # Note lack of parens for funcs
910
911 dispatch[get_input()]() # Note trailing parens to call function
912
913* Use the built-in function :func:`getattr`::
914
915 import foo
916 getattr(foo, 'bar')()
917
918 Note that :func:`getattr` works on any object, including classes, class
919 instances, modules, and so on.
920
921 This is used in several places in the standard library, like this::
922
923 class Foo:
924 def do_foo(self):
925 ...
926
927 def do_bar(self):
928 ...
929
930 f = getattr(foo_instance, 'do_' + opname)
931 f()
932
933
934* Use :func:`locals` or :func:`eval` to resolve the function name::
935
936 def myFunc():
Georg Brandl62eaaf62009-12-19 17:51:41 +0000937 print("hello")
Georg Brandld7413152009-10-11 21:25:26 +0000938
939 fname = "myFunc"
940
941 f = locals()[fname]
942 f()
943
944 f = eval(fname)
945 f()
946
947 Note: Using :func:`eval` is slow and dangerous. If you don't have absolute
948 control over the contents of the string, someone could pass a string that
949 resulted in an arbitrary function being executed.
950
951Is there an equivalent to Perl's chomp() for removing trailing newlines from strings?
952-------------------------------------------------------------------------------------
953
954Starting with Python 2.2, you can use ``S.rstrip("\r\n")`` to remove all
955occurences of any line terminator from the end of the string ``S`` without
956removing other trailing whitespace. If the string ``S`` represents more than
957one line, with several empty lines at the end, the line terminators for all the
958blank lines will be removed::
959
960 >>> lines = ("line 1 \r\n"
961 ... "\r\n"
962 ... "\r\n")
963 >>> lines.rstrip("\n\r")
Georg Brandl62eaaf62009-12-19 17:51:41 +0000964 'line 1 '
Georg Brandld7413152009-10-11 21:25:26 +0000965
966Since this is typically only desired when reading text one line at a time, using
967``S.rstrip()`` this way works well.
968
Georg Brandl62eaaf62009-12-19 17:51:41 +0000969For older versions of Python, there are two partial substitutes:
Georg Brandld7413152009-10-11 21:25:26 +0000970
971- If you want to remove all trailing whitespace, use the ``rstrip()`` method of
972 string objects. This removes all trailing whitespace, not just a single
973 newline.
974
975- Otherwise, if there is only one line in the string ``S``, use
976 ``S.splitlines()[0]``.
977
978
979Is there a scanf() or sscanf() equivalent?
980------------------------------------------
981
982Not as such.
983
984For simple input parsing, the easiest approach is usually to split the line into
985whitespace-delimited words using the :meth:`~str.split` method of string objects
986and then convert decimal strings to numeric values using :func:`int` or
987:func:`float`. ``split()`` supports an optional "sep" parameter which is useful
988if the line uses something other than whitespace as a separator.
989
990For more complicated input parsing, regular expressions more powerful than C's
991:cfunc:`sscanf` and better suited for the task.
992
993
Georg Brandl62eaaf62009-12-19 17:51:41 +0000994What does 'UnicodeDecodeError' or 'UnicodeEncodeError' error mean?
995-------------------------------------------------------------------
Georg Brandld7413152009-10-11 21:25:26 +0000996
Georg Brandl62eaaf62009-12-19 17:51:41 +0000997See the :ref:`unicode-howto`.
Georg Brandld7413152009-10-11 21:25:26 +0000998
999
1000Sequences (Tuples/Lists)
1001========================
1002
1003How do I convert between tuples and lists?
1004------------------------------------------
1005
1006The type constructor ``tuple(seq)`` converts any sequence (actually, any
1007iterable) into a tuple with the same items in the same order.
1008
1009For example, ``tuple([1, 2, 3])`` yields ``(1, 2, 3)`` and ``tuple('abc')``
1010yields ``('a', 'b', 'c')``. If the argument is a tuple, it does not make a copy
1011but returns the same object, so it is cheap to call :func:`tuple` when you
1012aren't sure that an object is already a tuple.
1013
1014The type constructor ``list(seq)`` converts any sequence or iterable into a list
1015with the same items in the same order. For example, ``list((1, 2, 3))`` yields
1016``[1, 2, 3]`` and ``list('abc')`` yields ``['a', 'b', 'c']``. If the argument
1017is a list, it makes a copy just like ``seq[:]`` would.
1018
1019
1020What's a negative index?
1021------------------------
1022
1023Python sequences are indexed with positive numbers and negative numbers. For
1024positive numbers 0 is the first index 1 is the second index and so forth. For
1025negative indices -1 is the last index and -2 is the penultimate (next to last)
1026index and so forth. Think of ``seq[-n]`` as the same as ``seq[len(seq)-n]``.
1027
1028Using negative indices can be very convenient. For example ``S[:-1]`` is all of
1029the string except for its last character, which is useful for removing the
1030trailing newline from a string.
1031
1032
1033How do I iterate over a sequence in reverse order?
1034--------------------------------------------------
1035
1036Use the :func:`reversed` builtin function, which is new in Python 2.4::
1037
1038 for x in reversed(sequence):
1039 ... # do something with x...
1040
1041This won't touch your original sequence, but build a new copy with reversed
1042order to iterate over.
1043
1044With Python 2.3, you can use an extended slice syntax::
1045
1046 for x in sequence[::-1]:
1047 ... # do something with x...
1048
1049
1050How do you remove duplicates from a list?
1051-----------------------------------------
1052
1053See the Python Cookbook for a long discussion of many ways to do this:
1054
1055 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52560
1056
1057If you don't mind reordering the list, sort it and then scan from the end of the
1058list, deleting duplicates as you go::
1059
Georg Brandl62eaaf62009-12-19 17:51:41 +00001060 if mylist:
1061 mylist.sort()
1062 last = mylist[-1]
1063 for i in range(len(mylist)-2, -1, -1):
1064 if last == mylist[i]:
1065 del mylist[i]
Georg Brandld7413152009-10-11 21:25:26 +00001066 else:
Georg Brandl62eaaf62009-12-19 17:51:41 +00001067 last = mylist[i]
Georg Brandld7413152009-10-11 21:25:26 +00001068
1069If all elements of the list may be used as dictionary keys (i.e. they are all
1070hashable) this is often faster ::
1071
1072 d = {}
Georg Brandl62eaaf62009-12-19 17:51:41 +00001073 for x in mylist:
1074 d[x] = 1
1075 mylist = list(d.keys())
Georg Brandld7413152009-10-11 21:25:26 +00001076
1077In Python 2.5 and later, the following is possible instead::
1078
Georg Brandl62eaaf62009-12-19 17:51:41 +00001079 mylist = list(set(mylist))
Georg Brandld7413152009-10-11 21:25:26 +00001080
1081This converts the list into a set, thereby removing duplicates, and then back
1082into a list.
1083
1084
1085How do you make an array in Python?
1086-----------------------------------
1087
1088Use a list::
1089
1090 ["this", 1, "is", "an", "array"]
1091
1092Lists are equivalent to C or Pascal arrays in their time complexity; the primary
1093difference is that a Python list can contain objects of many different types.
1094
1095The ``array`` module also provides methods for creating arrays of fixed types
1096with compact representations, but they are slower to index than lists. Also
1097note that the Numeric extensions and others define array-like structures with
1098various characteristics as well.
1099
1100To get Lisp-style linked lists, you can emulate cons cells using tuples::
1101
1102 lisp_list = ("like", ("this", ("example", None) ) )
1103
1104If mutability is desired, you could use lists instead of tuples. Here the
1105analogue of lisp car is ``lisp_list[0]`` and the analogue of cdr is
1106``lisp_list[1]``. Only do this if you're sure you really need to, because it's
1107usually a lot slower than using Python lists.
1108
1109
1110How do I create a multidimensional list?
1111----------------------------------------
1112
1113You probably tried to make a multidimensional array like this::
1114
1115 A = [[None] * 2] * 3
1116
1117This looks correct if you print it::
1118
1119 >>> A
1120 [[None, None], [None, None], [None, None]]
1121
1122But when you assign a value, it shows up in multiple places:
1123
1124 >>> A[0][0] = 5
1125 >>> A
1126 [[5, None], [5, None], [5, None]]
1127
1128The reason is that replicating a list with ``*`` doesn't create copies, it only
1129creates references to the existing objects. The ``*3`` creates a list
1130containing 3 references to the same list of length two. Changes to one row will
1131show in all rows, which is almost certainly not what you want.
1132
1133The suggested approach is to create a list of the desired length first and then
1134fill in each element with a newly created list::
1135
1136 A = [None] * 3
1137 for i in range(3):
1138 A[i] = [None] * 2
1139
1140This generates a list containing 3 different lists of length two. You can also
1141use a list comprehension::
1142
1143 w, h = 2, 3
1144 A = [[None] * w for i in range(h)]
1145
1146Or, you can use an extension that provides a matrix datatype; `Numeric Python
Georg Brandl495f7b52009-10-27 15:28:25 +00001147<http://numpy.scipy.org/>`_ is the best known.
Georg Brandld7413152009-10-11 21:25:26 +00001148
1149
1150How do I apply a method to a sequence of objects?
1151-------------------------------------------------
1152
1153Use a list comprehension::
1154
Georg Brandl62eaaf62009-12-19 17:51:41 +00001155 result = [obj.method() for obj in mylist]
Georg Brandld7413152009-10-11 21:25:26 +00001156
1157
1158Dictionaries
1159============
1160
1161How can I get a dictionary to display its keys in a consistent order?
1162---------------------------------------------------------------------
1163
1164You can't. Dictionaries store their keys in an unpredictable order, so the
1165display order of a dictionary's elements will be similarly unpredictable.
1166
1167This can be frustrating if you want to save a printable version to a file, make
1168some changes and then compare it with some other printed dictionary. In this
1169case, use the ``pprint`` module to pretty-print the dictionary; the items will
1170be presented in order sorted by the key.
1171
Georg Brandl62eaaf62009-12-19 17:51:41 +00001172A more complicated solution is to subclass ``dict`` to create a
Georg Brandld7413152009-10-11 21:25:26 +00001173``SortedDict`` class that prints itself in a predictable order. Here's one
1174simpleminded implementation of such a class::
1175
Georg Brandl62eaaf62009-12-19 17:51:41 +00001176 class SortedDict(dict):
Georg Brandld7413152009-10-11 21:25:26 +00001177 def __repr__(self):
Georg Brandl62eaaf62009-12-19 17:51:41 +00001178 keys = sorted(self.keys())
1179 result = ("{!r}: {!r}".format(k, self[k]) for k in keys)
1180 return "{{{}}}".format(", ".join(result))
Georg Brandld7413152009-10-11 21:25:26 +00001181
Georg Brandl62eaaf62009-12-19 17:51:41 +00001182 __str__ = __repr__
Georg Brandld7413152009-10-11 21:25:26 +00001183
1184This will work for many common situations you might encounter, though it's far
1185from a perfect solution. The largest flaw is that if some values in the
1186dictionary are also dictionaries, their values won't be presented in any
1187particular order.
1188
1189
1190I want to do a complicated sort: can you do a Schwartzian Transform in Python?
1191------------------------------------------------------------------------------
1192
1193The technique, attributed to Randal Schwartz of the Perl community, sorts the
1194elements of a list by a metric which maps each element to its "sort value". In
1195Python, just use the ``key`` argument for the ``sort()`` method::
1196
1197 Isorted = L[:]
1198 Isorted.sort(key=lambda s: int(s[10:15]))
1199
1200The ``key`` argument is new in Python 2.4, for older versions this kind of
1201sorting is quite simple to do with list comprehensions. To sort a list of
1202strings by their uppercase values::
1203
Georg Brandl62eaaf62009-12-19 17:51:41 +00001204 tmp1 = [(x.upper(), x) for x in L] # Schwartzian transform
Georg Brandld7413152009-10-11 21:25:26 +00001205 tmp1.sort()
1206 Usorted = [x[1] for x in tmp1]
1207
1208To sort by the integer value of a subfield extending from positions 10-15 in
1209each string::
1210
Georg Brandl62eaaf62009-12-19 17:51:41 +00001211 tmp2 = [(int(s[10:15]), s) for s in L] # Schwartzian transform
Georg Brandld7413152009-10-11 21:25:26 +00001212 tmp2.sort()
1213 Isorted = [x[1] for x in tmp2]
1214
Georg Brandl62eaaf62009-12-19 17:51:41 +00001215For versions prior to 3.0, Isorted may also be computed by ::
Georg Brandld7413152009-10-11 21:25:26 +00001216
1217 def intfield(s):
1218 return int(s[10:15])
1219
1220 def Icmp(s1, s2):
1221 return cmp(intfield(s1), intfield(s2))
1222
1223 Isorted = L[:]
1224 Isorted.sort(Icmp)
1225
1226but since this method calls ``intfield()`` many times for each element of L, it
1227is slower than the Schwartzian Transform.
1228
1229
1230How can I sort one list by values from another list?
1231----------------------------------------------------
1232
Georg Brandl62eaaf62009-12-19 17:51:41 +00001233Merge them into an iterator of tuples, sort the resulting list, and then pick
Georg Brandld7413152009-10-11 21:25:26 +00001234out the element you want. ::
1235
1236 >>> list1 = ["what", "I'm", "sorting", "by"]
1237 >>> list2 = ["something", "else", "to", "sort"]
1238 >>> pairs = zip(list1, list2)
Georg Brandl62eaaf62009-12-19 17:51:41 +00001239 >>> pairs = sorted(pairs)
Georg Brandld7413152009-10-11 21:25:26 +00001240 >>> pairs
Georg Brandl62eaaf62009-12-19 17:51:41 +00001241 [("I'm", 'else'), ('by', 'sort'), ('sorting', 'to'), ('what', 'something')]
1242 >>> result = [x[1] for x in pairs]
Georg Brandld7413152009-10-11 21:25:26 +00001243 >>> result
1244 ['else', 'sort', 'to', 'something']
1245
Georg Brandl62eaaf62009-12-19 17:51:41 +00001246
Georg Brandld7413152009-10-11 21:25:26 +00001247An alternative for the last step is::
1248
Georg Brandl62eaaf62009-12-19 17:51:41 +00001249 >>> result = []
1250 >>> for p in pairs: result.append(p[1])
Georg Brandld7413152009-10-11 21:25:26 +00001251
1252If you find this more legible, you might prefer to use this instead of the final
1253list comprehension. However, it is almost twice as slow for long lists. Why?
1254First, the ``append()`` operation has to reallocate memory, and while it uses
1255some tricks to avoid doing that each time, it still has to do it occasionally,
1256and that costs quite a bit. Second, the expression "result.append" requires an
1257extra attribute lookup, and third, there's a speed reduction from having to make
1258all those function calls.
1259
1260
1261Objects
1262=======
1263
1264What is a class?
1265----------------
1266
1267A class is the particular object type created by executing a class statement.
1268Class objects are used as templates to create instance objects, which embody
1269both the data (attributes) and code (methods) specific to a datatype.
1270
1271A class can be based on one or more other classes, called its base class(es). It
1272then inherits the attributes and methods of its base classes. This allows an
1273object model to be successively refined by inheritance. You might have a
1274generic ``Mailbox`` class that provides basic accessor methods for a mailbox,
1275and subclasses such as ``MboxMailbox``, ``MaildirMailbox``, ``OutlookMailbox``
1276that handle various specific mailbox formats.
1277
1278
1279What is a method?
1280-----------------
1281
1282A method is a function on some object ``x`` that you normally call as
1283``x.name(arguments...)``. Methods are defined as functions inside the class
1284definition::
1285
1286 class C:
1287 def meth (self, arg):
1288 return arg * 2 + self.attribute
1289
1290
1291What is self?
1292-------------
1293
1294Self is merely a conventional name for the first argument of a method. A method
1295defined as ``meth(self, a, b, c)`` should be called as ``x.meth(a, b, c)`` for
1296some instance ``x`` of the class in which the definition occurs; the called
1297method will think it is called as ``meth(x, a, b, c)``.
1298
1299See also :ref:`why-self`.
1300
1301
1302How do I check if an object is an instance of a given class or of a subclass of it?
1303-----------------------------------------------------------------------------------
1304
1305Use the built-in function ``isinstance(obj, cls)``. You can check if an object
1306is an instance of any of a number of classes by providing a tuple instead of a
1307single class, e.g. ``isinstance(obj, (class1, class2, ...))``, and can also
1308check whether an object is one of Python's built-in types, e.g.
Georg Brandl62eaaf62009-12-19 17:51:41 +00001309``isinstance(obj, str)`` or ``isinstance(obj, (int, float, complex))``.
Georg Brandld7413152009-10-11 21:25:26 +00001310
1311Note that most programs do not use :func:`isinstance` on user-defined classes
1312very often. If you are developing the classes yourself, a more proper
1313object-oriented style is to define methods on the classes that encapsulate a
1314particular behaviour, instead of checking the object's class and doing a
1315different thing based on what class it is. For example, if you have a function
1316that does something::
1317
Georg Brandl62eaaf62009-12-19 17:51:41 +00001318 def search(obj):
Georg Brandld7413152009-10-11 21:25:26 +00001319 if isinstance(obj, Mailbox):
1320 # ... code to search a mailbox
1321 elif isinstance(obj, Document):
1322 # ... code to search a document
1323 elif ...
1324
1325A better approach is to define a ``search()`` method on all the classes and just
1326call it::
1327
1328 class Mailbox:
1329 def search(self):
1330 # ... code to search a mailbox
1331
1332 class Document:
1333 def search(self):
1334 # ... code to search a document
1335
1336 obj.search()
1337
1338
1339What is delegation?
1340-------------------
1341
1342Delegation is an object oriented technique (also called a design pattern).
1343Let's say you have an object ``x`` and want to change the behaviour of just one
1344of its methods. You can create a new class that provides a new implementation
1345of the method you're interested in changing and delegates all other methods to
1346the corresponding method of ``x``.
1347
1348Python programmers can easily implement delegation. For example, the following
1349class implements a class that behaves like a file but converts all written data
1350to uppercase::
1351
1352 class UpperOut:
1353
1354 def __init__(self, outfile):
1355 self._outfile = outfile
1356
1357 def write(self, s):
1358 self._outfile.write(s.upper())
1359
1360 def __getattr__(self, name):
1361 return getattr(self._outfile, name)
1362
1363Here the ``UpperOut`` class redefines the ``write()`` method to convert the
1364argument string to uppercase before calling the underlying
1365``self.__outfile.write()`` method. All other methods are delegated to the
1366underlying ``self.__outfile`` object. The delegation is accomplished via the
1367``__getattr__`` method; consult :ref:`the language reference <attribute-access>`
1368for more information about controlling attribute access.
1369
1370Note that for more general cases delegation can get trickier. When attributes
1371must be set as well as retrieved, the class must define a :meth:`__setattr__`
1372method too, and it must do so carefully. The basic implementation of
1373:meth:`__setattr__` is roughly equivalent to the following::
1374
1375 class X:
1376 ...
1377 def __setattr__(self, name, value):
1378 self.__dict__[name] = value
1379 ...
1380
1381Most :meth:`__setattr__` implementations must modify ``self.__dict__`` to store
1382local state for self without causing an infinite recursion.
1383
1384
1385How do I call a method defined in a base class from a derived class that overrides it?
1386--------------------------------------------------------------------------------------
1387
Georg Brandl62eaaf62009-12-19 17:51:41 +00001388Use the built-in :func:`super` function::
Georg Brandld7413152009-10-11 21:25:26 +00001389
1390 class Derived(Base):
1391 def meth (self):
1392 super(Derived, self).meth()
1393
Georg Brandl62eaaf62009-12-19 17:51:41 +00001394For version prior to 3.0, you may be using classic classes: For a class
1395definition such as ``class Derived(Base): ...`` you can call method ``meth()``
1396defined in ``Base`` (or one of ``Base``'s base classes) as ``Base.meth(self,
1397arguments...)``. Here, ``Base.meth`` is an unbound method, so you need to
1398provide the ``self`` argument.
Georg Brandld7413152009-10-11 21:25:26 +00001399
1400
1401How can I organize my code to make it easier to change the base class?
1402----------------------------------------------------------------------
1403
1404You could define an alias for the base class, assign the real base class to it
1405before your class definition, and use the alias throughout your class. Then all
1406you have to change is the value assigned to the alias. Incidentally, this trick
1407is also handy if you want to decide dynamically (e.g. depending on availability
1408of resources) which base class to use. Example::
1409
1410 BaseAlias = <real base class>
1411
1412 class Derived(BaseAlias):
1413 def meth(self):
1414 BaseAlias.meth(self)
1415 ...
1416
1417
1418How do I create static class data and static class methods?
1419-----------------------------------------------------------
1420
Georg Brandl62eaaf62009-12-19 17:51:41 +00001421Both static data and static methods (in the sense of C++ or Java) are supported
1422in Python.
Georg Brandld7413152009-10-11 21:25:26 +00001423
1424For static data, simply define a class attribute. To assign a new value to the
1425attribute, you have to explicitly use the class name in the assignment::
1426
1427 class C:
1428 count = 0 # number of times C.__init__ called
1429
1430 def __init__(self):
1431 C.count = C.count + 1
1432
1433 def getcount(self):
1434 return C.count # or return self.count
1435
1436``c.count`` also refers to ``C.count`` for any ``c`` such that ``isinstance(c,
1437C)`` holds, unless overridden by ``c`` itself or by some class on the base-class
1438search path from ``c.__class__`` back to ``C``.
1439
1440Caution: within a method of C, an assignment like ``self.count = 42`` creates a
Georg Brandl62eaaf62009-12-19 17:51:41 +00001441new and unrelated instance named "count" in ``self``'s own dict. Rebinding of a
1442class-static data name must always specify the class whether inside a method or
1443not::
Georg Brandld7413152009-10-11 21:25:26 +00001444
1445 C.count = 314
1446
1447Static methods are possible since Python 2.2::
1448
1449 class C:
1450 def static(arg1, arg2, arg3):
1451 # No 'self' parameter!
1452 ...
1453 static = staticmethod(static)
1454
1455With Python 2.4's decorators, this can also be written as ::
1456
1457 class C:
1458 @staticmethod
1459 def static(arg1, arg2, arg3):
1460 # No 'self' parameter!
1461 ...
1462
1463However, a far more straightforward way to get the effect of a static method is
1464via a simple module-level function::
1465
1466 def getcount():
1467 return C.count
1468
1469If your code is structured so as to define one class (or tightly related class
1470hierarchy) per module, this supplies the desired encapsulation.
1471
1472
1473How can I overload constructors (or methods) in Python?
1474-------------------------------------------------------
1475
1476This answer actually applies to all methods, but the question usually comes up
1477first in the context of constructors.
1478
1479In C++ you'd write
1480
1481.. code-block:: c
1482
1483 class C {
1484 C() { cout << "No arguments\n"; }
1485 C(int i) { cout << "Argument is " << i << "\n"; }
1486 }
1487
1488In Python you have to write a single constructor that catches all cases using
1489default arguments. For example::
1490
1491 class C:
1492 def __init__(self, i=None):
1493 if i is None:
Georg Brandl62eaaf62009-12-19 17:51:41 +00001494 print("No arguments")
Georg Brandld7413152009-10-11 21:25:26 +00001495 else:
Georg Brandl62eaaf62009-12-19 17:51:41 +00001496 print("Argument is", i)
Georg Brandld7413152009-10-11 21:25:26 +00001497
1498This is not entirely equivalent, but close enough in practice.
1499
1500You could also try a variable-length argument list, e.g. ::
1501
1502 def __init__(self, *args):
1503 ...
1504
1505The same approach works for all method definitions.
1506
1507
1508I try to use __spam and I get an error about _SomeClassName__spam.
1509------------------------------------------------------------------
1510
1511Variable names with double leading underscores are "mangled" to provide a simple
1512but effective way to define class private variables. Any identifier of the form
1513``__spam`` (at least two leading underscores, at most one trailing underscore)
1514is textually replaced with ``_classname__spam``, where ``classname`` is the
1515current class name with any leading underscores stripped.
1516
1517This doesn't guarantee privacy: an outside user can still deliberately access
1518the "_classname__spam" attribute, and private values are visible in the object's
1519``__dict__``. Many Python programmers never bother to use private variable
1520names at all.
1521
1522
1523My class defines __del__ but it is not called when I delete the object.
1524-----------------------------------------------------------------------
1525
1526There are several possible reasons for this.
1527
1528The del statement does not necessarily call :meth:`__del__` -- it simply
1529decrements the object's reference count, and if this reaches zero
1530:meth:`__del__` is called.
1531
1532If your data structures contain circular links (e.g. a tree where each child has
1533a parent reference and each parent has a list of children) the reference counts
1534will never go back to zero. Once in a while Python runs an algorithm to detect
1535such cycles, but the garbage collector might run some time after the last
1536reference to your data structure vanishes, so your :meth:`__del__` method may be
1537called at an inconvenient and random time. This is inconvenient if you're trying
1538to reproduce a problem. Worse, the order in which object's :meth:`__del__`
1539methods are executed is arbitrary. You can run :func:`gc.collect` to force a
1540collection, but there *are* pathological cases where objects will never be
1541collected.
1542
1543Despite the cycle collector, it's still a good idea to define an explicit
1544``close()`` method on objects to be called whenever you're done with them. The
1545``close()`` method can then remove attributes that refer to subobjecs. Don't
1546call :meth:`__del__` directly -- :meth:`__del__` should call ``close()`` and
1547``close()`` should make sure that it can be called more than once for the same
1548object.
1549
1550Another way to avoid cyclical references is to use the :mod:`weakref` module,
1551which allows you to point to objects without incrementing their reference count.
1552Tree data structures, for instance, should use weak references for their parent
1553and sibling references (if they need them!).
1554
Georg Brandl62eaaf62009-12-19 17:51:41 +00001555.. XXX relevant for Python 3?
1556
1557 If the object has ever been a local variable in a function that caught an
1558 expression in an except clause, chances are that a reference to the object
1559 still exists in that function's stack frame as contained in the stack trace.
1560 Normally, calling :func:`sys.exc_clear` will take care of this by clearing
1561 the last recorded exception.
Georg Brandld7413152009-10-11 21:25:26 +00001562
1563Finally, if your :meth:`__del__` method raises an exception, a warning message
1564is printed to :data:`sys.stderr`.
1565
1566
1567How do I get a list of all instances of a given class?
1568------------------------------------------------------
1569
1570Python does not keep track of all instances of a class (or of a built-in type).
1571You can program the class's constructor to keep track of all instances by
1572keeping a list of weak references to each instance.
1573
1574
1575Modules
1576=======
1577
1578How do I create a .pyc file?
1579----------------------------
1580
1581When a module is imported for the first time (or when the source is more recent
1582than the current compiled file) a ``.pyc`` file containing the compiled code
1583should be created in the same directory as the ``.py`` file.
1584
1585One reason that a ``.pyc`` file may not be created is permissions problems with
1586the directory. This can happen, for example, if you develop as one user but run
1587as another, such as if you are testing with a web server. Creation of a .pyc
1588file is automatic if you're importing a module and Python has the ability
1589(permissions, free space, etc...) to write the compiled module back to the
1590directory.
1591
1592Running Python on a top level script is not considered an import and no ``.pyc``
1593will be created. For example, if you have a top-level module ``abc.py`` that
1594imports another module ``xyz.py``, when you run abc, ``xyz.pyc`` will be created
1595since xyz is imported, but no ``abc.pyc`` file will be created since ``abc.py``
1596isn't being imported.
1597
1598If you need to create abc.pyc -- that is, to create a .pyc file for a module
1599that is not imported -- you can, using the :mod:`py_compile` and
1600:mod:`compileall` modules.
1601
1602The :mod:`py_compile` module can manually compile any module. One way is to use
1603the ``compile()`` function in that module interactively::
1604
1605 >>> import py_compile
1606 >>> py_compile.compile('abc.py')
1607
1608This will write the ``.pyc`` to the same location as ``abc.py`` (or you can
1609override that with the optional parameter ``cfile``).
1610
1611You can also automatically compile all files in a directory or directories using
1612the :mod:`compileall` module. You can do it from the shell prompt by running
1613``compileall.py`` and providing the path of a directory containing Python files
1614to compile::
1615
1616 python -m compileall .
1617
1618
1619How do I find the current module name?
1620--------------------------------------
1621
1622A module can find out its own module name by looking at the predefined global
1623variable ``__name__``. If this has the value ``'__main__'``, the program is
1624running as a script. Many modules that are usually used by importing them also
1625provide a command-line interface or a self-test, and only execute this code
1626after checking ``__name__``::
1627
1628 def main():
Georg Brandl62eaaf62009-12-19 17:51:41 +00001629 print('Running test...')
Georg Brandld7413152009-10-11 21:25:26 +00001630 ...
1631
1632 if __name__ == '__main__':
1633 main()
1634
1635
1636How can I have modules that mutually import each other?
1637-------------------------------------------------------
1638
1639Suppose you have the following modules:
1640
1641foo.py::
1642
1643 from bar import bar_var
1644 foo_var = 1
1645
1646bar.py::
1647
1648 from foo import foo_var
1649 bar_var = 2
1650
1651The problem is that the interpreter will perform the following steps:
1652
1653* main imports foo
1654* Empty globals for foo are created
1655* foo is compiled and starts executing
1656* foo imports bar
1657* Empty globals for bar are created
1658* bar is compiled and starts executing
1659* bar imports foo (which is a no-op since there already is a module named foo)
1660* bar.foo_var = foo.foo_var
1661
1662The last step fails, because Python isn't done with interpreting ``foo`` yet and
1663the global symbol dictionary for ``foo`` is still empty.
1664
1665The same thing happens when you use ``import foo``, and then try to access
1666``foo.foo_var`` in global code.
1667
1668There are (at least) three possible workarounds for this problem.
1669
1670Guido van Rossum recommends avoiding all uses of ``from <module> import ...``,
1671and placing all code inside functions. Initializations of global variables and
1672class variables should use constants or built-in functions only. This means
1673everything from an imported module is referenced as ``<module>.<name>``.
1674
1675Jim Roskind suggests performing steps in the following order in each module:
1676
1677* exports (globals, functions, and classes that don't need imported base
1678 classes)
1679* ``import`` statements
1680* active code (including globals that are initialized from imported values).
1681
1682van Rossum doesn't like this approach much because the imports appear in a
1683strange place, but it does work.
1684
1685Matthias Urlichs recommends restructuring your code so that the recursive import
1686is not necessary in the first place.
1687
1688These solutions are not mutually exclusive.
1689
1690
1691__import__('x.y.z') returns <module 'x'>; how do I get z?
1692---------------------------------------------------------
1693
1694Try::
1695
1696 __import__('x.y.z').y.z
1697
1698For more realistic situations, you may have to do something like ::
1699
1700 m = __import__(s)
1701 for i in s.split(".")[1:]:
1702 m = getattr(m, i)
1703
1704See :mod:`importlib` for a convenience function called
1705:func:`~importlib.import_module`.
1706
1707
1708
1709When I edit an imported module and reimport it, the changes don't show up. Why does this happen?
1710-------------------------------------------------------------------------------------------------
1711
1712For reasons of efficiency as well as consistency, Python only reads the module
1713file on the first time a module is imported. If it didn't, in a program
1714consisting of many modules where each one imports the same basic module, the
1715basic module would be parsed and re-parsed many times. To force rereading of a
1716changed module, do this::
1717
Georg Brandl62eaaf62009-12-19 17:51:41 +00001718 import imp
Georg Brandld7413152009-10-11 21:25:26 +00001719 import modname
Georg Brandl62eaaf62009-12-19 17:51:41 +00001720 imp.reload(modname)
Georg Brandld7413152009-10-11 21:25:26 +00001721
1722Warning: this technique is not 100% fool-proof. In particular, modules
1723containing statements like ::
1724
1725 from modname import some_objects
1726
1727will continue to work with the old version of the imported objects. If the
1728module contains class definitions, existing class instances will *not* be
1729updated to use the new class definition. This can result in the following
1730paradoxical behaviour:
1731
Georg Brandl62eaaf62009-12-19 17:51:41 +00001732 >>> import imp
Georg Brandld7413152009-10-11 21:25:26 +00001733 >>> import cls
1734 >>> c = cls.C() # Create an instance of C
Georg Brandl62eaaf62009-12-19 17:51:41 +00001735 >>> imp.reload(cls)
1736 <module 'cls' from 'cls.py'>
Georg Brandld7413152009-10-11 21:25:26 +00001737 >>> isinstance(c, cls.C) # isinstance is false?!?
1738 False
1739
Georg Brandl62eaaf62009-12-19 17:51:41 +00001740The nature of the problem is made clear if you print out the "identity" of the
1741class objects:
Georg Brandld7413152009-10-11 21:25:26 +00001742
Georg Brandl62eaaf62009-12-19 17:51:41 +00001743 >>> hex(id(c.__class__))
1744 '0x7352a0'
1745 >>> hex(id(cls.C))
1746 '0x4198d0'