blob: 8fc7666811c3509d038e35a8a8fa255f492b308f [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 Brandl62eaaf62009-12-19 17:51:41 +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
195Other examples include the ``join()`` and ``split()`` methods of string objects.
196For example if s1..s7 are large (10K+) strings then
197``"".join([s1,s2,s3,s4,s5,s6,s7])`` may be far faster than the more obvious
198``s1+s2+s3+s4+s5+s6+s7``, since the "summation" will compute many
199subexpressions, whereas ``join()`` does all the copying in one pass. For
Georg Brandl62eaaf62009-12-19 17:51:41 +0000200manipulating strings, use the ``replace()`` and the ``format()`` methods on
201string objects. Use regular expressions only when you're not dealing with
202constant string patterns.
Georg Brandld7413152009-10-11 21:25:26 +0000203
204Be sure to use the :meth:`list.sort` builtin method to do sorting, and see the
205`sorting mini-HOWTO <http://wiki.python.org/moin/HowTo/Sorting>`_ for examples
206of moderately advanced usage. :meth:`list.sort` beats other techniques for
207sorting in all but the most extreme circumstances.
208
209Another common trick is to "push loops into functions or methods." For example
210suppose you have a program that runs slowly and you use the profiler to
211determine that a Python function ``ff()`` is being called lots of times. If you
Georg Brandl62eaaf62009-12-19 17:51:41 +0000212notice that ``ff()``::
Georg Brandld7413152009-10-11 21:25:26 +0000213
214 def ff(x):
215 ... # do something with x computing result...
216 return result
217
218tends to be called in loops like::
219
220 list = map(ff, oldlist)
221
222or::
223
224 for x in sequence:
225 value = ff(x)
226 ... # do something with value...
227
228then you can often eliminate function call overhead by rewriting ``ff()`` to::
229
230 def ffseq(seq):
231 resultseq = []
232 for x in seq:
233 ... # do something with x computing result...
234 resultseq.append(result)
235 return resultseq
236
237and rewrite the two examples to ``list = ffseq(oldlist)`` and to::
238
239 for value in ffseq(sequence):
240 ... # do something with value...
241
242Single calls to ``ff(x)`` translate to ``ffseq([x])[0]`` with little penalty.
243Of course this technique is not always appropriate and there are other variants
244which you can figure out.
245
246You can gain some performance by explicitly storing the results of a function or
247method lookup into a local variable. A loop like::
248
249 for key in token:
250 dict[key] = dict.get(key, 0) + 1
251
252resolves ``dict.get`` every iteration. If the method isn't going to change, a
253slightly faster implementation is::
254
255 dict_get = dict.get # look up the method once
256 for key in token:
257 dict[key] = dict_get(key, 0) + 1
258
259Default arguments can be used to determine values once, at compile time instead
260of at run time. This can only be done for functions or objects which will not
261be changed during program execution, such as replacing ::
262
263 def degree_sin(deg):
264 return math.sin(deg * math.pi / 180.0)
265
266with ::
267
268 def degree_sin(deg, factor=math.pi/180.0, sin=math.sin):
269 return sin(deg * factor)
270
271Because this trick uses default arguments for terms which should not be changed,
272it should only be used when you are not concerned with presenting a possibly
273confusing API to your users.
274
275
276Core Language
277=============
278
R. David Murrayc04a6942009-11-14 22:21:32 +0000279Why am I getting an UnboundLocalError when the variable has a value?
280--------------------------------------------------------------------
Georg Brandld7413152009-10-11 21:25:26 +0000281
R. David Murrayc04a6942009-11-14 22:21:32 +0000282It can be a surprise to get the UnboundLocalError in previously working
283code when it is modified by adding an assignment statement somewhere in
284the body of a function.
Georg Brandld7413152009-10-11 21:25:26 +0000285
R. David Murrayc04a6942009-11-14 22:21:32 +0000286This code:
Georg Brandld7413152009-10-11 21:25:26 +0000287
R. David Murrayc04a6942009-11-14 22:21:32 +0000288 >>> x = 10
289 >>> def bar():
290 ... print(x)
291 >>> bar()
292 10
Georg Brandld7413152009-10-11 21:25:26 +0000293
R. David Murrayc04a6942009-11-14 22:21:32 +0000294works, but this code:
Georg Brandld7413152009-10-11 21:25:26 +0000295
R. David Murrayc04a6942009-11-14 22:21:32 +0000296 >>> x = 10
297 >>> def foo():
298 ... print(x)
299 ... x += 1
Georg Brandld7413152009-10-11 21:25:26 +0000300
R. David Murrayc04a6942009-11-14 22:21:32 +0000301results in an UnboundLocalError:
Georg Brandld7413152009-10-11 21:25:26 +0000302
R. David Murrayc04a6942009-11-14 22:21:32 +0000303 >>> foo()
304 Traceback (most recent call last):
305 ...
306 UnboundLocalError: local variable 'x' referenced before assignment
307
308This is because when you make an assignment to a variable in a scope, that
309variable becomes local to that scope and shadows any similarly named variable
310in the outer scope. Since the last statement in foo assigns a new value to
311``x``, the compiler recognizes it as a local variable. Consequently when the
R. David Murray18163c32009-11-14 22:27:22 +0000312earlier ``print(x)`` attempts to print the uninitialized local variable and
R. David Murrayc04a6942009-11-14 22:21:32 +0000313an error results.
314
315In the example above you can access the outer scope variable by declaring it
316global:
317
318 >>> x = 10
319 >>> def foobar():
320 ... global x
321 ... print(x)
322 ... x += 1
323 >>> foobar()
324 10
325
326This explicit declaration is required in order to remind you that (unlike the
327superficially analogous situation with class and instance variables) you are
328actually modifying the value of the variable in the outer scope:
329
330 >>> print(x)
331 11
332
333You can do a similar thing in a nested scope using the :keyword:`nonlocal`
334keyword:
335
336 >>> def foo():
337 ... x = 10
338 ... def bar():
339 ... nonlocal x
340 ... print(x)
341 ... x += 1
342 ... bar()
343 ... print(x)
344 >>> foo()
345 10
346 11
Georg Brandld7413152009-10-11 21:25:26 +0000347
348
349What are the rules for local and global variables in Python?
350------------------------------------------------------------
351
352In Python, variables that are only referenced inside a function are implicitly
353global. If a variable is assigned a new value anywhere within the function's
354body, it's assumed to be a local. If a variable is ever assigned a new value
355inside the function, the variable is implicitly local, and you need to
356explicitly declare it as 'global'.
357
358Though a bit surprising at first, a moment's consideration explains this. On
359one hand, requiring :keyword:`global` for assigned variables provides a bar
360against unintended side-effects. On the other hand, if ``global`` was required
361for all global references, you'd be using ``global`` all the time. You'd have
362to declare as global every reference to a builtin function or to a component of
363an imported module. This clutter would defeat the usefulness of the ``global``
364declaration for identifying side-effects.
365
366
367How do I share global variables across modules?
368------------------------------------------------
369
370The canonical way to share information across modules within a single program is
371to create a special module (often called config or cfg). Just import the config
372module in all modules of your application; the module then becomes available as
373a global name. Because there is only one instance of each module, any changes
374made to the module object get reflected everywhere. For example:
375
376config.py::
377
378 x = 0 # Default value of the 'x' configuration setting
379
380mod.py::
381
382 import config
383 config.x = 1
384
385main.py::
386
387 import config
388 import mod
Georg Brandl62eaaf62009-12-19 17:51:41 +0000389 print(config.x)
Georg Brandld7413152009-10-11 21:25:26 +0000390
391Note that using a module is also the basis for implementing the Singleton design
392pattern, for the same reason.
393
394
395What are the "best practices" for using import in a module?
396-----------------------------------------------------------
397
398In general, don't use ``from modulename import *``. Doing so clutters the
399importer's namespace. Some people avoid this idiom even with the few modules
400that were designed to be imported in this manner. Modules designed in this
Georg Brandld404fa62009-10-13 16:55:12 +0000401manner include :mod:`tkinter`, and :mod:`threading`.
Georg Brandld7413152009-10-11 21:25:26 +0000402
403Import modules at the top of a file. Doing so makes it clear what other modules
404your code requires and avoids questions of whether the module name is in scope.
405Using one import per line makes it easy to add and delete module imports, but
406using multiple imports per line uses less screen space.
407
408It's good practice if you import modules in the following order:
409
Georg Brandl62eaaf62009-12-19 17:51:41 +00004101. standard library modules -- e.g. ``sys``, ``os``, ``getopt``, ``re``
Georg Brandld7413152009-10-11 21:25:26 +00004112. third-party library modules (anything installed in Python's site-packages
412 directory) -- e.g. mx.DateTime, ZODB, PIL.Image, etc.
4133. locally-developed modules
414
415Never use relative package imports. If you're writing code that's in the
416``package.sub.m1`` module and want to import ``package.sub.m2``, do not just
Georg Brandl62eaaf62009-12-19 17:51:41 +0000417write ``from . import m2``, even though it's legal. Write ``from package.sub import
418m2`` instead. See :pep:`328` for details.
Georg Brandld7413152009-10-11 21:25:26 +0000419
420It is sometimes necessary to move imports to a function or class to avoid
421problems with circular imports. Gordon McMillan says:
422
423 Circular imports are fine where both modules use the "import <module>" form
424 of import. They fail when the 2nd module wants to grab a name out of the
425 first ("from module import name") and the import is at the top level. That's
426 because names in the 1st are not yet available, because the first module is
427 busy importing the 2nd.
428
429In this case, if the second module is only used in one function, then the import
430can easily be moved into that function. By the time the import is called, the
431first module will have finished initializing, and the second module can do its
432import.
433
434It may also be necessary to move imports out of the top level of code if some of
435the modules are platform-specific. In that case, it may not even be possible to
436import all of the modules at the top of the file. In this case, importing the
437correct modules in the corresponding platform-specific code is a good option.
438
439Only move imports into a local scope, such as inside a function definition, if
440it's necessary to solve a problem such as avoiding a circular import or are
441trying to reduce the initialization time of a module. This technique is
442especially helpful if many of the imports are unnecessary depending on how the
443program executes. You may also want to move imports into a function if the
444modules are only ever used in that function. Note that loading a module the
445first time may be expensive because of the one time initialization of the
446module, but loading a module multiple times is virtually free, costing only a
447couple of dictionary lookups. Even if the module name has gone out of scope,
448the module is probably available in :data:`sys.modules`.
449
450If only instances of a specific class use a module, then it is reasonable to
451import the module in the class's ``__init__`` method and then assign the module
452to an instance variable so that the module is always available (via that
453instance variable) during the life of the object. Note that to delay an import
454until the class is instantiated, the import must be inside a method. Putting
455the import inside the class but outside of any method still causes the import to
456occur when the module is initialized.
457
458
459How can I pass optional or keyword parameters from one function to another?
460---------------------------------------------------------------------------
461
462Collect the arguments using the ``*`` and ``**`` specifiers in the function's
463parameter list; this gives you the positional arguments as a tuple and the
464keyword arguments as a dictionary. You can then pass these arguments when
465calling another function by using ``*`` and ``**``::
466
467 def f(x, *args, **kwargs):
468 ...
469 kwargs['width'] = '14.3c'
470 ...
471 g(x, *args, **kwargs)
472
473In the unlikely case that you care about Python versions older than 2.0, use
474:func:`apply`::
475
476 def f(x, *args, **kwargs):
477 ...
478 kwargs['width'] = '14.3c'
479 ...
480 apply(g, (x,)+args, kwargs)
481
482
483How do I write a function with output parameters (call by reference)?
484---------------------------------------------------------------------
485
486Remember that arguments are passed by assignment in Python. Since assignment
487just creates references to objects, there's no alias between an argument name in
488the caller and callee, and so no call-by-reference per se. You can achieve the
489desired effect in a number of ways.
490
4911) By returning a tuple of the results::
492
493 def func2(a, b):
494 a = 'new-value' # a and b are local names
495 b = b + 1 # assigned to new objects
496 return a, b # return new values
497
498 x, y = 'old-value', 99
499 x, y = func2(x, y)
Georg Brandl62eaaf62009-12-19 17:51:41 +0000500 print(x, y) # output: new-value 100
Georg Brandld7413152009-10-11 21:25:26 +0000501
502 This is almost always the clearest solution.
503
5042) By using global variables. This isn't thread-safe, and is not recommended.
505
5063) By passing a mutable (changeable in-place) object::
507
508 def func1(a):
509 a[0] = 'new-value' # 'a' references a mutable list
510 a[1] = a[1] + 1 # changes a shared object
511
512 args = ['old-value', 99]
513 func1(args)
Georg Brandl62eaaf62009-12-19 17:51:41 +0000514 print(args[0], args[1]) # output: new-value 100
Georg Brandld7413152009-10-11 21:25:26 +0000515
5164) By passing in a dictionary that gets mutated::
517
518 def func3(args):
519 args['a'] = 'new-value' # args is a mutable dictionary
520 args['b'] = args['b'] + 1 # change it in-place
521
522 args = {'a':' old-value', 'b': 99}
523 func3(args)
Georg Brandl62eaaf62009-12-19 17:51:41 +0000524 print(args['a'], args['b'])
Georg Brandld7413152009-10-11 21:25:26 +0000525
5265) Or bundle up values in a class instance::
527
528 class callByRef:
529 def __init__(self, **args):
530 for (key, value) in args.items():
531 setattr(self, key, value)
532
533 def func4(args):
534 args.a = 'new-value' # args is a mutable callByRef
535 args.b = args.b + 1 # change object in-place
536
537 args = callByRef(a='old-value', b=99)
538 func4(args)
Georg Brandl62eaaf62009-12-19 17:51:41 +0000539 print(args.a, args.b)
Georg Brandld7413152009-10-11 21:25:26 +0000540
541
542 There's almost never a good reason to get this complicated.
543
544Your best choice is to return a tuple containing the multiple results.
545
546
547How do you make a higher order function in Python?
548--------------------------------------------------
549
550You have two choices: you can use nested scopes or you can use callable objects.
551For example, suppose you wanted to define ``linear(a,b)`` which returns a
552function ``f(x)`` that computes the value ``a*x+b``. Using nested scopes::
553
554 def linear(a, b):
555 def result(x):
556 return a * x + b
557 return result
558
559Or using a callable object::
560
561 class linear:
562
563 def __init__(self, a, b):
564 self.a, self.b = a, b
565
566 def __call__(self, x):
567 return self.a * x + self.b
568
569In both cases, ::
570
571 taxes = linear(0.3, 2)
572
573gives a callable object where ``taxes(10e6) == 0.3 * 10e6 + 2``.
574
575The callable object approach has the disadvantage that it is a bit slower and
576results in slightly longer code. However, note that a collection of callables
577can share their signature via inheritance::
578
579 class exponential(linear):
580 # __init__ inherited
581 def __call__(self, x):
582 return self.a * (x ** self.b)
583
584Object can encapsulate state for several methods::
585
586 class counter:
587
588 value = 0
589
590 def set(self, x):
591 self.value = x
592
593 def up(self):
594 self.value = self.value + 1
595
596 def down(self):
597 self.value = self.value - 1
598
599 count = counter()
600 inc, dec, reset = count.up, count.down, count.set
601
602Here ``inc()``, ``dec()`` and ``reset()`` act like functions which share the
603same counting variable.
604
605
606How do I copy an object in Python?
607----------------------------------
608
609In general, try :func:`copy.copy` or :func:`copy.deepcopy` for the general case.
610Not all objects can be copied, but most can.
611
612Some objects can be copied more easily. Dictionaries have a :meth:`~dict.copy`
613method::
614
615 newdict = olddict.copy()
616
617Sequences can be copied by slicing::
618
619 new_l = l[:]
620
621
622How can I find the methods or attributes of an object?
623------------------------------------------------------
624
625For an instance x of a user-defined class, ``dir(x)`` returns an alphabetized
626list of the names containing the instance attributes and methods and attributes
627defined by its class.
628
629
630How can my code discover the name of an object?
631-----------------------------------------------
632
633Generally speaking, it can't, because objects don't really have names.
634Essentially, assignment always binds a name to a value; The same is true of
635``def`` and ``class`` statements, but in that case the value is a
636callable. Consider the following code::
637
638 class A:
639 pass
640
641 B = A
642
643 a = B()
644 b = a
Georg Brandl62eaaf62009-12-19 17:51:41 +0000645 print(b)
646 <__main__.A object at 0x16D07CC>
647 print(a)
648 <__main__.A object at 0x16D07CC>
Georg Brandld7413152009-10-11 21:25:26 +0000649
650Arguably the class has a name: even though it is bound to two names and invoked
651through the name B the created instance is still reported as an instance of
652class A. However, it is impossible to say whether the instance's name is a or
653b, since both names are bound to the same value.
654
655Generally speaking it should not be necessary for your code to "know the names"
656of particular values. Unless you are deliberately writing introspective
657programs, this is usually an indication that a change of approach might be
658beneficial.
659
660In comp.lang.python, Fredrik Lundh once gave an excellent analogy in answer to
661this question:
662
663 The same way as you get the name of that cat you found on your porch: the cat
664 (object) itself cannot tell you its name, and it doesn't really care -- so
665 the only way to find out what it's called is to ask all your neighbours
666 (namespaces) if it's their cat (object)...
667
668 ....and don't be surprised if you'll find that it's known by many names, or
669 no name at all!
670
671
672What's up with the comma operator's precedence?
673-----------------------------------------------
674
675Comma is not an operator in Python. Consider this session::
676
677 >>> "a" in "b", "a"
Georg Brandl62eaaf62009-12-19 17:51:41 +0000678 (False, 'a')
Georg Brandld7413152009-10-11 21:25:26 +0000679
680Since the comma is not an operator, but a separator between expressions the
681above is evaluated as if you had entered::
682
683 >>> ("a" in "b"), "a"
684
685not::
686
Georg Brandl62eaaf62009-12-19 17:51:41 +0000687 >>> "a" in ("b", "a")
Georg Brandld7413152009-10-11 21:25:26 +0000688
689The same is true of the various assignment operators (``=``, ``+=`` etc). They
690are not truly operators but syntactic delimiters in assignment statements.
691
692
693Is there an equivalent of C's "?:" ternary operator?
694----------------------------------------------------
695
696Yes, this feature was added in Python 2.5. The syntax would be as follows::
697
698 [on_true] if [expression] else [on_false]
699
700 x, y = 50, 25
701
702 small = x if x < y else y
703
704For versions previous to 2.5 the answer would be 'No'.
705
706.. XXX remove rest?
707
708In many cases you can mimic ``a ? b : c`` with ``a and b or c``, but there's a
709flaw: if *b* is zero (or empty, or ``None`` -- anything that tests false) then
710*c* will be selected instead. In many cases you can prove by looking at the
711code that this can't happen (e.g. because *b* is a constant or has a type that
712can never be false), but in general this can be a problem.
713
714Tim Peters (who wishes it was Steve Majewski) suggested the following solution:
715``(a and [b] or [c])[0]``. Because ``[b]`` is a singleton list it is never
716false, so the wrong path is never taken; then applying ``[0]`` to the whole
717thing gets the *b* or *c* that you really wanted. Ugly, but it gets you there
718in the rare cases where it is really inconvenient to rewrite your code using
719'if'.
720
721The best course is usually to write a simple ``if...else`` statement. Another
722solution is to implement the ``?:`` operator as a function::
723
724 def q(cond, on_true, on_false):
725 if cond:
726 if not isfunction(on_true):
727 return on_true
728 else:
Georg Brandl62eaaf62009-12-19 17:51:41 +0000729 return on_true()
Georg Brandld7413152009-10-11 21:25:26 +0000730 else:
731 if not isfunction(on_false):
732 return on_false
733 else:
Georg Brandl62eaaf62009-12-19 17:51:41 +0000734 return on_false()
Georg Brandld7413152009-10-11 21:25:26 +0000735
736In most cases you'll pass b and c directly: ``q(a, b, c)``. To avoid evaluating
737b or c when they shouldn't be, encapsulate them within a lambda function, e.g.:
738``q(a, lambda: b, lambda: c)``.
739
740It has been asked *why* Python has no if-then-else expression. There are
741several answers: many languages do just fine without one; it can easily lead to
742less readable code; no sufficiently "Pythonic" syntax has been discovered; a
743search of the standard library found remarkably few places where using an
744if-then-else expression would make the code more understandable.
745
746In 2002, :pep:`308` was written proposing several possible syntaxes and the
747community was asked to vote on the issue. The vote was inconclusive. Most
748people liked one of the syntaxes, but also hated other syntaxes; many votes
749implied that people preferred no ternary operator rather than having a syntax
750they hated.
751
752
753Is it possible to write obfuscated one-liners in Python?
754--------------------------------------------------------
755
756Yes. Usually this is done by nesting :keyword:`lambda` within
757:keyword:`lambda`. See the following three examples, due to Ulf Bartelt::
758
Georg Brandl62eaaf62009-12-19 17:51:41 +0000759 from functools import reduce
760
Georg Brandld7413152009-10-11 21:25:26 +0000761 # Primes < 1000
Georg Brandl62eaaf62009-12-19 17:51:41 +0000762 print(list(filter(None,map(lambda y:y*reduce(lambda x,y:x*y!=0,
763 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 +0000764
765 # First 10 Fibonacci numbers
Georg Brandl62eaaf62009-12-19 17:51:41 +0000766 print(list(map(lambda x,f=lambda x,f:(f(x-1,f)+f(x-2,f)) if x>1 else 1:
767 f(x,f), range(10))))
Georg Brandld7413152009-10-11 21:25:26 +0000768
769 # Mandelbrot set
Georg Brandl62eaaf62009-12-19 17:51:41 +0000770 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 +0000771 Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,Sy=Sy,L=lambda yc,Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,i=IM,
772 Sx=Sx,Sy=Sy:reduce(lambda x,y:x+y,map(lambda x,xc=Ru,yc=yc,Ru=Ru,Ro=Ro,
773 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
774 >=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(
775 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 +0000776 ))))(-2.1, 0.7, -1.2, 1.2, 30, 80, 24))
Georg Brandld7413152009-10-11 21:25:26 +0000777 # \___ ___/ \___ ___/ | | |__ lines on screen
778 # V V | |______ columns on screen
779 # | | |__________ maximum of "iterations"
780 # | |_________________ range on y axis
781 # |____________________________ range on x axis
782
783Don't try this at home, kids!
784
785
786Numbers and strings
787===================
788
789How do I specify hexadecimal and octal integers?
790------------------------------------------------
791
Georg Brandl62eaaf62009-12-19 17:51:41 +0000792To specify an octal digit, precede the octal value with a zero, and then a lower
793or uppercase "o". For example, to set the variable "a" to the octal value "10"
794(8 in decimal), type::
Georg Brandld7413152009-10-11 21:25:26 +0000795
Georg Brandl62eaaf62009-12-19 17:51:41 +0000796 >>> a = 0o10
Georg Brandld7413152009-10-11 21:25:26 +0000797 >>> a
798 8
799
800Hexadecimal is just as easy. Simply precede the hexadecimal number with a zero,
801and then a lower or uppercase "x". Hexadecimal digits can be specified in lower
802or uppercase. For example, in the Python interpreter::
803
804 >>> a = 0xa5
805 >>> a
806 165
807 >>> b = 0XB2
808 >>> b
809 178
810
811
Georg Brandl62eaaf62009-12-19 17:51:41 +0000812Why does -22 // 10 return -3?
813-----------------------------
Georg Brandld7413152009-10-11 21:25:26 +0000814
815It's primarily driven by the desire that ``i % j`` have the same sign as ``j``.
816If you want that, and also want::
817
Georg Brandl62eaaf62009-12-19 17:51:41 +0000818 i == (i // j) * j + (i % j)
Georg Brandld7413152009-10-11 21:25:26 +0000819
820then integer division has to return the floor. C also requires that identity to
Georg Brandl62eaaf62009-12-19 17:51:41 +0000821hold, and then compilers that truncate ``i // j`` need to make ``i % j`` have
822the same sign as ``i``.
Georg Brandld7413152009-10-11 21:25:26 +0000823
824There are few real use cases for ``i % j`` when ``j`` is negative. When ``j``
825is positive, there are many, and in virtually all of them it's more useful for
826``i % j`` to be ``>= 0``. If the clock says 10 now, what did it say 200 hours
827ago? ``-190 % 12 == 2`` is useful; ``-190 % 12 == -10`` is a bug waiting to
828bite.
829
830
831How do I convert a string to a number?
832--------------------------------------
833
834For integers, use the built-in :func:`int` type constructor, e.g. ``int('144')
835== 144``. Similarly, :func:`float` converts to floating-point,
836e.g. ``float('144') == 144.0``.
837
838By default, these interpret the number as decimal, so that ``int('0144') ==
839144`` and ``int('0x144')`` raises :exc:`ValueError`. ``int(string, base)`` takes
840the base to convert from as a second optional argument, so ``int('0x144', 16) ==
841324``. If the base is specified as 0, the number is interpreted using Python's
842rules: a leading '0' indicates octal, and '0x' indicates a hex number.
843
844Do not use the built-in function :func:`eval` if all you need is to convert
845strings to numbers. :func:`eval` will be significantly slower and it presents a
846security risk: someone could pass you a Python expression that might have
847unwanted side effects. For example, someone could pass
848``__import__('os').system("rm -rf $HOME")`` which would erase your home
849directory.
850
851:func:`eval` also has the effect of interpreting numbers as Python expressions,
Georg Brandl62eaaf62009-12-19 17:51:41 +0000852so that e.g. ``eval('09')`` gives a syntax error because Python does not allow
853leading '0' in a decimal number (except '0').
Georg Brandld7413152009-10-11 21:25:26 +0000854
855
856How do I convert a number to a string?
857--------------------------------------
858
859To convert, e.g., the number 144 to the string '144', use the built-in type
860constructor :func:`str`. If you want a hexadecimal or octal representation, use
Georg Brandl62eaaf62009-12-19 17:51:41 +0000861the built-in functions :func:`hex` or :func:`oct`. For fancy formatting, see
862the :ref:`string-formatting` section, e.g. ``"{:04d}".format(144)`` yields
863``'0144'`` and ``"{:.3f}" % (1/3)`` yields ``'0.333'``.
Georg Brandld7413152009-10-11 21:25:26 +0000864
865
866How do I modify a string in place?
867----------------------------------
868
869You can't, because strings are immutable. If you need an object with this
870ability, try converting the string to a list or use the array module::
871
872 >>> s = "Hello, world"
873 >>> a = list(s)
Georg Brandl62eaaf62009-12-19 17:51:41 +0000874 >>> print(a)
Georg Brandld7413152009-10-11 21:25:26 +0000875 ['H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd']
876 >>> a[7:] = list("there!")
877 >>> ''.join(a)
878 'Hello, there!'
879
880 >>> import array
Georg Brandl62eaaf62009-12-19 17:51:41 +0000881 >>> a = array.array('u', s)
882 >>> print(a)
883 array('u', 'Hello, world')
884 >>> a[0] = 'y'
885 >>> print(a)
886 array('u', 'yello world')
887 >>> a.tounicode()
Georg Brandld7413152009-10-11 21:25:26 +0000888 'yello, world'
889
890
891How do I use strings to call functions/methods?
892-----------------------------------------------
893
894There are various techniques.
895
896* The best is to use a dictionary that maps strings to functions. The primary
897 advantage of this technique is that the strings do not need to match the names
898 of the functions. This is also the primary technique used to emulate a case
899 construct::
900
901 def a():
902 pass
903
904 def b():
905 pass
906
907 dispatch = {'go': a, 'stop': b} # Note lack of parens for funcs
908
909 dispatch[get_input()]() # Note trailing parens to call function
910
911* Use the built-in function :func:`getattr`::
912
913 import foo
914 getattr(foo, 'bar')()
915
916 Note that :func:`getattr` works on any object, including classes, class
917 instances, modules, and so on.
918
919 This is used in several places in the standard library, like this::
920
921 class Foo:
922 def do_foo(self):
923 ...
924
925 def do_bar(self):
926 ...
927
928 f = getattr(foo_instance, 'do_' + opname)
929 f()
930
931
932* Use :func:`locals` or :func:`eval` to resolve the function name::
933
934 def myFunc():
Georg Brandl62eaaf62009-12-19 17:51:41 +0000935 print("hello")
Georg Brandld7413152009-10-11 21:25:26 +0000936
937 fname = "myFunc"
938
939 f = locals()[fname]
940 f()
941
942 f = eval(fname)
943 f()
944
945 Note: Using :func:`eval` is slow and dangerous. If you don't have absolute
946 control over the contents of the string, someone could pass a string that
947 resulted in an arbitrary function being executed.
948
949Is there an equivalent to Perl's chomp() for removing trailing newlines from strings?
950-------------------------------------------------------------------------------------
951
952Starting with Python 2.2, you can use ``S.rstrip("\r\n")`` to remove all
953occurences of any line terminator from the end of the string ``S`` without
954removing other trailing whitespace. If the string ``S`` represents more than
955one line, with several empty lines at the end, the line terminators for all the
956blank lines will be removed::
957
958 >>> lines = ("line 1 \r\n"
959 ... "\r\n"
960 ... "\r\n")
961 >>> lines.rstrip("\n\r")
Georg Brandl62eaaf62009-12-19 17:51:41 +0000962 'line 1 '
Georg Brandld7413152009-10-11 21:25:26 +0000963
964Since this is typically only desired when reading text one line at a time, using
965``S.rstrip()`` this way works well.
966
Georg Brandl62eaaf62009-12-19 17:51:41 +0000967For older versions of Python, there are two partial substitutes:
Georg Brandld7413152009-10-11 21:25:26 +0000968
969- If you want to remove all trailing whitespace, use the ``rstrip()`` method of
970 string objects. This removes all trailing whitespace, not just a single
971 newline.
972
973- Otherwise, if there is only one line in the string ``S``, use
974 ``S.splitlines()[0]``.
975
976
977Is there a scanf() or sscanf() equivalent?
978------------------------------------------
979
980Not as such.
981
982For simple input parsing, the easiest approach is usually to split the line into
983whitespace-delimited words using the :meth:`~str.split` method of string objects
984and then convert decimal strings to numeric values using :func:`int` or
985:func:`float`. ``split()`` supports an optional "sep" parameter which is useful
986if the line uses something other than whitespace as a separator.
987
988For more complicated input parsing, regular expressions more powerful than C's
989:cfunc:`sscanf` and better suited for the task.
990
991
Georg Brandl62eaaf62009-12-19 17:51:41 +0000992What does 'UnicodeDecodeError' or 'UnicodeEncodeError' error mean?
993-------------------------------------------------------------------
Georg Brandld7413152009-10-11 21:25:26 +0000994
Georg Brandl62eaaf62009-12-19 17:51:41 +0000995See the :ref:`unicode-howto`.
Georg Brandld7413152009-10-11 21:25:26 +0000996
997
998Sequences (Tuples/Lists)
999========================
1000
1001How do I convert between tuples and lists?
1002------------------------------------------
1003
1004The type constructor ``tuple(seq)`` converts any sequence (actually, any
1005iterable) into a tuple with the same items in the same order.
1006
1007For example, ``tuple([1, 2, 3])`` yields ``(1, 2, 3)`` and ``tuple('abc')``
1008yields ``('a', 'b', 'c')``. If the argument is a tuple, it does not make a copy
1009but returns the same object, so it is cheap to call :func:`tuple` when you
1010aren't sure that an object is already a tuple.
1011
1012The type constructor ``list(seq)`` converts any sequence or iterable into a list
1013with the same items in the same order. For example, ``list((1, 2, 3))`` yields
1014``[1, 2, 3]`` and ``list('abc')`` yields ``['a', 'b', 'c']``. If the argument
1015is a list, it makes a copy just like ``seq[:]`` would.
1016
1017
1018What's a negative index?
1019------------------------
1020
1021Python sequences are indexed with positive numbers and negative numbers. For
1022positive numbers 0 is the first index 1 is the second index and so forth. For
1023negative indices -1 is the last index and -2 is the penultimate (next to last)
1024index and so forth. Think of ``seq[-n]`` as the same as ``seq[len(seq)-n]``.
1025
1026Using negative indices can be very convenient. For example ``S[:-1]`` is all of
1027the string except for its last character, which is useful for removing the
1028trailing newline from a string.
1029
1030
1031How do I iterate over a sequence in reverse order?
1032--------------------------------------------------
1033
1034Use the :func:`reversed` builtin function, which is new in Python 2.4::
1035
1036 for x in reversed(sequence):
1037 ... # do something with x...
1038
1039This won't touch your original sequence, but build a new copy with reversed
1040order to iterate over.
1041
1042With Python 2.3, you can use an extended slice syntax::
1043
1044 for x in sequence[::-1]:
1045 ... # do something with x...
1046
1047
1048How do you remove duplicates from a list?
1049-----------------------------------------
1050
1051See the Python Cookbook for a long discussion of many ways to do this:
1052
1053 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52560
1054
1055If you don't mind reordering the list, sort it and then scan from the end of the
1056list, deleting duplicates as you go::
1057
Georg Brandl62eaaf62009-12-19 17:51:41 +00001058 if mylist:
1059 mylist.sort()
1060 last = mylist[-1]
1061 for i in range(len(mylist)-2, -1, -1):
1062 if last == mylist[i]:
1063 del mylist[i]
Georg Brandld7413152009-10-11 21:25:26 +00001064 else:
Georg Brandl62eaaf62009-12-19 17:51:41 +00001065 last = mylist[i]
Georg Brandld7413152009-10-11 21:25:26 +00001066
1067If all elements of the list may be used as dictionary keys (i.e. they are all
1068hashable) this is often faster ::
1069
1070 d = {}
Georg Brandl62eaaf62009-12-19 17:51:41 +00001071 for x in mylist:
1072 d[x] = 1
1073 mylist = list(d.keys())
Georg Brandld7413152009-10-11 21:25:26 +00001074
1075In Python 2.5 and later, the following is possible instead::
1076
Georg Brandl62eaaf62009-12-19 17:51:41 +00001077 mylist = list(set(mylist))
Georg Brandld7413152009-10-11 21:25:26 +00001078
1079This converts the list into a set, thereby removing duplicates, and then back
1080into a list.
1081
1082
1083How do you make an array in Python?
1084-----------------------------------
1085
1086Use a list::
1087
1088 ["this", 1, "is", "an", "array"]
1089
1090Lists are equivalent to C or Pascal arrays in their time complexity; the primary
1091difference is that a Python list can contain objects of many different types.
1092
1093The ``array`` module also provides methods for creating arrays of fixed types
1094with compact representations, but they are slower to index than lists. Also
1095note that the Numeric extensions and others define array-like structures with
1096various characteristics as well.
1097
1098To get Lisp-style linked lists, you can emulate cons cells using tuples::
1099
1100 lisp_list = ("like", ("this", ("example", None) ) )
1101
1102If mutability is desired, you could use lists instead of tuples. Here the
1103analogue of lisp car is ``lisp_list[0]`` and the analogue of cdr is
1104``lisp_list[1]``. Only do this if you're sure you really need to, because it's
1105usually a lot slower than using Python lists.
1106
1107
1108How do I create a multidimensional list?
1109----------------------------------------
1110
1111You probably tried to make a multidimensional array like this::
1112
1113 A = [[None] * 2] * 3
1114
1115This looks correct if you print it::
1116
1117 >>> A
1118 [[None, None], [None, None], [None, None]]
1119
1120But when you assign a value, it shows up in multiple places:
1121
1122 >>> A[0][0] = 5
1123 >>> A
1124 [[5, None], [5, None], [5, None]]
1125
1126The reason is that replicating a list with ``*`` doesn't create copies, it only
1127creates references to the existing objects. The ``*3`` creates a list
1128containing 3 references to the same list of length two. Changes to one row will
1129show in all rows, which is almost certainly not what you want.
1130
1131The suggested approach is to create a list of the desired length first and then
1132fill in each element with a newly created list::
1133
1134 A = [None] * 3
1135 for i in range(3):
1136 A[i] = [None] * 2
1137
1138This generates a list containing 3 different lists of length two. You can also
1139use a list comprehension::
1140
1141 w, h = 2, 3
1142 A = [[None] * w for i in range(h)]
1143
1144Or, you can use an extension that provides a matrix datatype; `Numeric Python
Georg Brandl495f7b52009-10-27 15:28:25 +00001145<http://numpy.scipy.org/>`_ is the best known.
Georg Brandld7413152009-10-11 21:25:26 +00001146
1147
1148How do I apply a method to a sequence of objects?
1149-------------------------------------------------
1150
1151Use a list comprehension::
1152
Georg Brandl62eaaf62009-12-19 17:51:41 +00001153 result = [obj.method() for obj in mylist]
Georg Brandld7413152009-10-11 21:25:26 +00001154
1155
1156Dictionaries
1157============
1158
1159How can I get a dictionary to display its keys in a consistent order?
1160---------------------------------------------------------------------
1161
1162You can't. Dictionaries store their keys in an unpredictable order, so the
1163display order of a dictionary's elements will be similarly unpredictable.
1164
1165This can be frustrating if you want to save a printable version to a file, make
1166some changes and then compare it with some other printed dictionary. In this
1167case, use the ``pprint`` module to pretty-print the dictionary; the items will
1168be presented in order sorted by the key.
1169
Georg Brandl62eaaf62009-12-19 17:51:41 +00001170A more complicated solution is to subclass ``dict`` to create a
Georg Brandld7413152009-10-11 21:25:26 +00001171``SortedDict`` class that prints itself in a predictable order. Here's one
1172simpleminded implementation of such a class::
1173
Georg Brandl62eaaf62009-12-19 17:51:41 +00001174 class SortedDict(dict):
Georg Brandld7413152009-10-11 21:25:26 +00001175 def __repr__(self):
Georg Brandl62eaaf62009-12-19 17:51:41 +00001176 keys = sorted(self.keys())
1177 result = ("{!r}: {!r}".format(k, self[k]) for k in keys)
1178 return "{{{}}}".format(", ".join(result))
Georg Brandld7413152009-10-11 21:25:26 +00001179
Georg Brandl62eaaf62009-12-19 17:51:41 +00001180 __str__ = __repr__
Georg Brandld7413152009-10-11 21:25:26 +00001181
1182This will work for many common situations you might encounter, though it's far
1183from a perfect solution. The largest flaw is that if some values in the
1184dictionary are also dictionaries, their values won't be presented in any
1185particular order.
1186
1187
1188I want to do a complicated sort: can you do a Schwartzian Transform in Python?
1189------------------------------------------------------------------------------
1190
1191The technique, attributed to Randal Schwartz of the Perl community, sorts the
1192elements of a list by a metric which maps each element to its "sort value". In
1193Python, just use the ``key`` argument for the ``sort()`` method::
1194
1195 Isorted = L[:]
1196 Isorted.sort(key=lambda s: int(s[10:15]))
1197
1198The ``key`` argument is new in Python 2.4, for older versions this kind of
1199sorting is quite simple to do with list comprehensions. To sort a list of
1200strings by their uppercase values::
1201
Georg Brandl62eaaf62009-12-19 17:51:41 +00001202 tmp1 = [(x.upper(), x) for x in L] # Schwartzian transform
Georg Brandld7413152009-10-11 21:25:26 +00001203 tmp1.sort()
1204 Usorted = [x[1] for x in tmp1]
1205
1206To sort by the integer value of a subfield extending from positions 10-15 in
1207each string::
1208
Georg Brandl62eaaf62009-12-19 17:51:41 +00001209 tmp2 = [(int(s[10:15]), s) for s in L] # Schwartzian transform
Georg Brandld7413152009-10-11 21:25:26 +00001210 tmp2.sort()
1211 Isorted = [x[1] for x in tmp2]
1212
Georg Brandl62eaaf62009-12-19 17:51:41 +00001213For versions prior to 3.0, Isorted may also be computed by ::
Georg Brandld7413152009-10-11 21:25:26 +00001214
1215 def intfield(s):
1216 return int(s[10:15])
1217
1218 def Icmp(s1, s2):
1219 return cmp(intfield(s1), intfield(s2))
1220
1221 Isorted = L[:]
1222 Isorted.sort(Icmp)
1223
1224but since this method calls ``intfield()`` many times for each element of L, it
1225is slower than the Schwartzian Transform.
1226
1227
1228How can I sort one list by values from another list?
1229----------------------------------------------------
1230
Georg Brandl62eaaf62009-12-19 17:51:41 +00001231Merge them into an iterator of tuples, sort the resulting list, and then pick
Georg Brandld7413152009-10-11 21:25:26 +00001232out the element you want. ::
1233
1234 >>> list1 = ["what", "I'm", "sorting", "by"]
1235 >>> list2 = ["something", "else", "to", "sort"]
1236 >>> pairs = zip(list1, list2)
Georg Brandl62eaaf62009-12-19 17:51:41 +00001237 >>> pairs = sorted(pairs)
Georg Brandld7413152009-10-11 21:25:26 +00001238 >>> pairs
Georg Brandl62eaaf62009-12-19 17:51:41 +00001239 [("I'm", 'else'), ('by', 'sort'), ('sorting', 'to'), ('what', 'something')]
1240 >>> result = [x[1] for x in pairs]
Georg Brandld7413152009-10-11 21:25:26 +00001241 >>> result
1242 ['else', 'sort', 'to', 'something']
1243
Georg Brandl62eaaf62009-12-19 17:51:41 +00001244
Georg Brandld7413152009-10-11 21:25:26 +00001245An alternative for the last step is::
1246
Georg Brandl62eaaf62009-12-19 17:51:41 +00001247 >>> result = []
1248 >>> for p in pairs: result.append(p[1])
Georg Brandld7413152009-10-11 21:25:26 +00001249
1250If you find this more legible, you might prefer to use this instead of the final
1251list comprehension. However, it is almost twice as slow for long lists. Why?
1252First, the ``append()`` operation has to reallocate memory, and while it uses
1253some tricks to avoid doing that each time, it still has to do it occasionally,
1254and that costs quite a bit. Second, the expression "result.append" requires an
1255extra attribute lookup, and third, there's a speed reduction from having to make
1256all those function calls.
1257
1258
1259Objects
1260=======
1261
1262What is a class?
1263----------------
1264
1265A class is the particular object type created by executing a class statement.
1266Class objects are used as templates to create instance objects, which embody
1267both the data (attributes) and code (methods) specific to a datatype.
1268
1269A class can be based on one or more other classes, called its base class(es). It
1270then inherits the attributes and methods of its base classes. This allows an
1271object model to be successively refined by inheritance. You might have a
1272generic ``Mailbox`` class that provides basic accessor methods for a mailbox,
1273and subclasses such as ``MboxMailbox``, ``MaildirMailbox``, ``OutlookMailbox``
1274that handle various specific mailbox formats.
1275
1276
1277What is a method?
1278-----------------
1279
1280A method is a function on some object ``x`` that you normally call as
1281``x.name(arguments...)``. Methods are defined as functions inside the class
1282definition::
1283
1284 class C:
1285 def meth (self, arg):
1286 return arg * 2 + self.attribute
1287
1288
1289What is self?
1290-------------
1291
1292Self is merely a conventional name for the first argument of a method. A method
1293defined as ``meth(self, a, b, c)`` should be called as ``x.meth(a, b, c)`` for
1294some instance ``x`` of the class in which the definition occurs; the called
1295method will think it is called as ``meth(x, a, b, c)``.
1296
1297See also :ref:`why-self`.
1298
1299
1300How do I check if an object is an instance of a given class or of a subclass of it?
1301-----------------------------------------------------------------------------------
1302
1303Use the built-in function ``isinstance(obj, cls)``. You can check if an object
1304is an instance of any of a number of classes by providing a tuple instead of a
1305single class, e.g. ``isinstance(obj, (class1, class2, ...))``, and can also
1306check whether an object is one of Python's built-in types, e.g.
Georg Brandl62eaaf62009-12-19 17:51:41 +00001307``isinstance(obj, str)`` or ``isinstance(obj, (int, float, complex))``.
Georg Brandld7413152009-10-11 21:25:26 +00001308
1309Note that most programs do not use :func:`isinstance` on user-defined classes
1310very often. If you are developing the classes yourself, a more proper
1311object-oriented style is to define methods on the classes that encapsulate a
1312particular behaviour, instead of checking the object's class and doing a
1313different thing based on what class it is. For example, if you have a function
1314that does something::
1315
Georg Brandl62eaaf62009-12-19 17:51:41 +00001316 def search(obj):
Georg Brandld7413152009-10-11 21:25:26 +00001317 if isinstance(obj, Mailbox):
1318 # ... code to search a mailbox
1319 elif isinstance(obj, Document):
1320 # ... code to search a document
1321 elif ...
1322
1323A better approach is to define a ``search()`` method on all the classes and just
1324call it::
1325
1326 class Mailbox:
1327 def search(self):
1328 # ... code to search a mailbox
1329
1330 class Document:
1331 def search(self):
1332 # ... code to search a document
1333
1334 obj.search()
1335
1336
1337What is delegation?
1338-------------------
1339
1340Delegation is an object oriented technique (also called a design pattern).
1341Let's say you have an object ``x`` and want to change the behaviour of just one
1342of its methods. You can create a new class that provides a new implementation
1343of the method you're interested in changing and delegates all other methods to
1344the corresponding method of ``x``.
1345
1346Python programmers can easily implement delegation. For example, the following
1347class implements a class that behaves like a file but converts all written data
1348to uppercase::
1349
1350 class UpperOut:
1351
1352 def __init__(self, outfile):
1353 self._outfile = outfile
1354
1355 def write(self, s):
1356 self._outfile.write(s.upper())
1357
1358 def __getattr__(self, name):
1359 return getattr(self._outfile, name)
1360
1361Here the ``UpperOut`` class redefines the ``write()`` method to convert the
1362argument string to uppercase before calling the underlying
1363``self.__outfile.write()`` method. All other methods are delegated to the
1364underlying ``self.__outfile`` object. The delegation is accomplished via the
1365``__getattr__`` method; consult :ref:`the language reference <attribute-access>`
1366for more information about controlling attribute access.
1367
1368Note that for more general cases delegation can get trickier. When attributes
1369must be set as well as retrieved, the class must define a :meth:`__setattr__`
1370method too, and it must do so carefully. The basic implementation of
1371:meth:`__setattr__` is roughly equivalent to the following::
1372
1373 class X:
1374 ...
1375 def __setattr__(self, name, value):
1376 self.__dict__[name] = value
1377 ...
1378
1379Most :meth:`__setattr__` implementations must modify ``self.__dict__`` to store
1380local state for self without causing an infinite recursion.
1381
1382
1383How do I call a method defined in a base class from a derived class that overrides it?
1384--------------------------------------------------------------------------------------
1385
Georg Brandl62eaaf62009-12-19 17:51:41 +00001386Use the built-in :func:`super` function::
Georg Brandld7413152009-10-11 21:25:26 +00001387
1388 class Derived(Base):
1389 def meth (self):
1390 super(Derived, self).meth()
1391
Georg Brandl62eaaf62009-12-19 17:51:41 +00001392For version prior to 3.0, you may be using classic classes: For a class
1393definition such as ``class Derived(Base): ...`` you can call method ``meth()``
1394defined in ``Base`` (or one of ``Base``'s base classes) as ``Base.meth(self,
1395arguments...)``. Here, ``Base.meth`` is an unbound method, so you need to
1396provide the ``self`` argument.
Georg Brandld7413152009-10-11 21:25:26 +00001397
1398
1399How can I organize my code to make it easier to change the base class?
1400----------------------------------------------------------------------
1401
1402You could define an alias for the base class, assign the real base class to it
1403before your class definition, and use the alias throughout your class. Then all
1404you have to change is the value assigned to the alias. Incidentally, this trick
1405is also handy if you want to decide dynamically (e.g. depending on availability
1406of resources) which base class to use. Example::
1407
1408 BaseAlias = <real base class>
1409
1410 class Derived(BaseAlias):
1411 def meth(self):
1412 BaseAlias.meth(self)
1413 ...
1414
1415
1416How do I create static class data and static class methods?
1417-----------------------------------------------------------
1418
Georg Brandl62eaaf62009-12-19 17:51:41 +00001419Both static data and static methods (in the sense of C++ or Java) are supported
1420in Python.
Georg Brandld7413152009-10-11 21:25:26 +00001421
1422For static data, simply define a class attribute. To assign a new value to the
1423attribute, you have to explicitly use the class name in the assignment::
1424
1425 class C:
1426 count = 0 # number of times C.__init__ called
1427
1428 def __init__(self):
1429 C.count = C.count + 1
1430
1431 def getcount(self):
1432 return C.count # or return self.count
1433
1434``c.count`` also refers to ``C.count`` for any ``c`` such that ``isinstance(c,
1435C)`` holds, unless overridden by ``c`` itself or by some class on the base-class
1436search path from ``c.__class__`` back to ``C``.
1437
1438Caution: within a method of C, an assignment like ``self.count = 42`` creates a
Georg Brandl62eaaf62009-12-19 17:51:41 +00001439new and unrelated instance named "count" in ``self``'s own dict. Rebinding of a
1440class-static data name must always specify the class whether inside a method or
1441not::
Georg Brandld7413152009-10-11 21:25:26 +00001442
1443 C.count = 314
1444
1445Static methods are possible since Python 2.2::
1446
1447 class C:
1448 def static(arg1, arg2, arg3):
1449 # No 'self' parameter!
1450 ...
1451 static = staticmethod(static)
1452
1453With Python 2.4's decorators, this can also be written as ::
1454
1455 class C:
1456 @staticmethod
1457 def static(arg1, arg2, arg3):
1458 # No 'self' parameter!
1459 ...
1460
1461However, a far more straightforward way to get the effect of a static method is
1462via a simple module-level function::
1463
1464 def getcount():
1465 return C.count
1466
1467If your code is structured so as to define one class (or tightly related class
1468hierarchy) per module, this supplies the desired encapsulation.
1469
1470
1471How can I overload constructors (or methods) in Python?
1472-------------------------------------------------------
1473
1474This answer actually applies to all methods, but the question usually comes up
1475first in the context of constructors.
1476
1477In C++ you'd write
1478
1479.. code-block:: c
1480
1481 class C {
1482 C() { cout << "No arguments\n"; }
1483 C(int i) { cout << "Argument is " << i << "\n"; }
1484 }
1485
1486In Python you have to write a single constructor that catches all cases using
1487default arguments. For example::
1488
1489 class C:
1490 def __init__(self, i=None):
1491 if i is None:
Georg Brandl62eaaf62009-12-19 17:51:41 +00001492 print("No arguments")
Georg Brandld7413152009-10-11 21:25:26 +00001493 else:
Georg Brandl62eaaf62009-12-19 17:51:41 +00001494 print("Argument is", i)
Georg Brandld7413152009-10-11 21:25:26 +00001495
1496This is not entirely equivalent, but close enough in practice.
1497
1498You could also try a variable-length argument list, e.g. ::
1499
1500 def __init__(self, *args):
1501 ...
1502
1503The same approach works for all method definitions.
1504
1505
1506I try to use __spam and I get an error about _SomeClassName__spam.
1507------------------------------------------------------------------
1508
1509Variable names with double leading underscores are "mangled" to provide a simple
1510but effective way to define class private variables. Any identifier of the form
1511``__spam`` (at least two leading underscores, at most one trailing underscore)
1512is textually replaced with ``_classname__spam``, where ``classname`` is the
1513current class name with any leading underscores stripped.
1514
1515This doesn't guarantee privacy: an outside user can still deliberately access
1516the "_classname__spam" attribute, and private values are visible in the object's
1517``__dict__``. Many Python programmers never bother to use private variable
1518names at all.
1519
1520
1521My class defines __del__ but it is not called when I delete the object.
1522-----------------------------------------------------------------------
1523
1524There are several possible reasons for this.
1525
1526The del statement does not necessarily call :meth:`__del__` -- it simply
1527decrements the object's reference count, and if this reaches zero
1528:meth:`__del__` is called.
1529
1530If your data structures contain circular links (e.g. a tree where each child has
1531a parent reference and each parent has a list of children) the reference counts
1532will never go back to zero. Once in a while Python runs an algorithm to detect
1533such cycles, but the garbage collector might run some time after the last
1534reference to your data structure vanishes, so your :meth:`__del__` method may be
1535called at an inconvenient and random time. This is inconvenient if you're trying
1536to reproduce a problem. Worse, the order in which object's :meth:`__del__`
1537methods are executed is arbitrary. You can run :func:`gc.collect` to force a
1538collection, but there *are* pathological cases where objects will never be
1539collected.
1540
1541Despite the cycle collector, it's still a good idea to define an explicit
1542``close()`` method on objects to be called whenever you're done with them. The
1543``close()`` method can then remove attributes that refer to subobjecs. Don't
1544call :meth:`__del__` directly -- :meth:`__del__` should call ``close()`` and
1545``close()`` should make sure that it can be called more than once for the same
1546object.
1547
1548Another way to avoid cyclical references is to use the :mod:`weakref` module,
1549which allows you to point to objects without incrementing their reference count.
1550Tree data structures, for instance, should use weak references for their parent
1551and sibling references (if they need them!).
1552
Georg Brandl62eaaf62009-12-19 17:51:41 +00001553.. XXX relevant for Python 3?
1554
1555 If the object has ever been a local variable in a function that caught an
1556 expression in an except clause, chances are that a reference to the object
1557 still exists in that function's stack frame as contained in the stack trace.
1558 Normally, calling :func:`sys.exc_clear` will take care of this by clearing
1559 the last recorded exception.
Georg Brandld7413152009-10-11 21:25:26 +00001560
1561Finally, if your :meth:`__del__` method raises an exception, a warning message
1562is printed to :data:`sys.stderr`.
1563
1564
1565How do I get a list of all instances of a given class?
1566------------------------------------------------------
1567
1568Python does not keep track of all instances of a class (or of a built-in type).
1569You can program the class's constructor to keep track of all instances by
1570keeping a list of weak references to each instance.
1571
1572
1573Modules
1574=======
1575
1576How do I create a .pyc file?
1577----------------------------
1578
1579When a module is imported for the first time (or when the source is more recent
1580than the current compiled file) a ``.pyc`` file containing the compiled code
1581should be created in the same directory as the ``.py`` file.
1582
1583One reason that a ``.pyc`` file may not be created is permissions problems with
1584the directory. This can happen, for example, if you develop as one user but run
1585as another, such as if you are testing with a web server. Creation of a .pyc
1586file is automatic if you're importing a module and Python has the ability
1587(permissions, free space, etc...) to write the compiled module back to the
1588directory.
1589
1590Running Python on a top level script is not considered an import and no ``.pyc``
1591will be created. For example, if you have a top-level module ``abc.py`` that
1592imports another module ``xyz.py``, when you run abc, ``xyz.pyc`` will be created
1593since xyz is imported, but no ``abc.pyc`` file will be created since ``abc.py``
1594isn't being imported.
1595
1596If you need to create abc.pyc -- that is, to create a .pyc file for a module
1597that is not imported -- you can, using the :mod:`py_compile` and
1598:mod:`compileall` modules.
1599
1600The :mod:`py_compile` module can manually compile any module. One way is to use
1601the ``compile()`` function in that module interactively::
1602
1603 >>> import py_compile
1604 >>> py_compile.compile('abc.py')
1605
1606This will write the ``.pyc`` to the same location as ``abc.py`` (or you can
1607override that with the optional parameter ``cfile``).
1608
1609You can also automatically compile all files in a directory or directories using
1610the :mod:`compileall` module. You can do it from the shell prompt by running
1611``compileall.py`` and providing the path of a directory containing Python files
1612to compile::
1613
1614 python -m compileall .
1615
1616
1617How do I find the current module name?
1618--------------------------------------
1619
1620A module can find out its own module name by looking at the predefined global
1621variable ``__name__``. If this has the value ``'__main__'``, the program is
1622running as a script. Many modules that are usually used by importing them also
1623provide a command-line interface or a self-test, and only execute this code
1624after checking ``__name__``::
1625
1626 def main():
Georg Brandl62eaaf62009-12-19 17:51:41 +00001627 print('Running test...')
Georg Brandld7413152009-10-11 21:25:26 +00001628 ...
1629
1630 if __name__ == '__main__':
1631 main()
1632
1633
1634How can I have modules that mutually import each other?
1635-------------------------------------------------------
1636
1637Suppose you have the following modules:
1638
1639foo.py::
1640
1641 from bar import bar_var
1642 foo_var = 1
1643
1644bar.py::
1645
1646 from foo import foo_var
1647 bar_var = 2
1648
1649The problem is that the interpreter will perform the following steps:
1650
1651* main imports foo
1652* Empty globals for foo are created
1653* foo is compiled and starts executing
1654* foo imports bar
1655* Empty globals for bar are created
1656* bar is compiled and starts executing
1657* bar imports foo (which is a no-op since there already is a module named foo)
1658* bar.foo_var = foo.foo_var
1659
1660The last step fails, because Python isn't done with interpreting ``foo`` yet and
1661the global symbol dictionary for ``foo`` is still empty.
1662
1663The same thing happens when you use ``import foo``, and then try to access
1664``foo.foo_var`` in global code.
1665
1666There are (at least) three possible workarounds for this problem.
1667
1668Guido van Rossum recommends avoiding all uses of ``from <module> import ...``,
1669and placing all code inside functions. Initializations of global variables and
1670class variables should use constants or built-in functions only. This means
1671everything from an imported module is referenced as ``<module>.<name>``.
1672
1673Jim Roskind suggests performing steps in the following order in each module:
1674
1675* exports (globals, functions, and classes that don't need imported base
1676 classes)
1677* ``import`` statements
1678* active code (including globals that are initialized from imported values).
1679
1680van Rossum doesn't like this approach much because the imports appear in a
1681strange place, but it does work.
1682
1683Matthias Urlichs recommends restructuring your code so that the recursive import
1684is not necessary in the first place.
1685
1686These solutions are not mutually exclusive.
1687
1688
1689__import__('x.y.z') returns <module 'x'>; how do I get z?
1690---------------------------------------------------------
1691
1692Try::
1693
1694 __import__('x.y.z').y.z
1695
1696For more realistic situations, you may have to do something like ::
1697
1698 m = __import__(s)
1699 for i in s.split(".")[1:]:
1700 m = getattr(m, i)
1701
1702See :mod:`importlib` for a convenience function called
1703:func:`~importlib.import_module`.
1704
1705
1706
1707When I edit an imported module and reimport it, the changes don't show up. Why does this happen?
1708-------------------------------------------------------------------------------------------------
1709
1710For reasons of efficiency as well as consistency, Python only reads the module
1711file on the first time a module is imported. If it didn't, in a program
1712consisting of many modules where each one imports the same basic module, the
1713basic module would be parsed and re-parsed many times. To force rereading of a
1714changed module, do this::
1715
Georg Brandl62eaaf62009-12-19 17:51:41 +00001716 import imp
Georg Brandld7413152009-10-11 21:25:26 +00001717 import modname
Georg Brandl62eaaf62009-12-19 17:51:41 +00001718 imp.reload(modname)
Georg Brandld7413152009-10-11 21:25:26 +00001719
1720Warning: this technique is not 100% fool-proof. In particular, modules
1721containing statements like ::
1722
1723 from modname import some_objects
1724
1725will continue to work with the old version of the imported objects. If the
1726module contains class definitions, existing class instances will *not* be
1727updated to use the new class definition. This can result in the following
1728paradoxical behaviour:
1729
Georg Brandl62eaaf62009-12-19 17:51:41 +00001730 >>> import imp
Georg Brandld7413152009-10-11 21:25:26 +00001731 >>> import cls
1732 >>> c = cls.C() # Create an instance of C
Georg Brandl62eaaf62009-12-19 17:51:41 +00001733 >>> imp.reload(cls)
1734 <module 'cls' from 'cls.py'>
Georg Brandld7413152009-10-11 21:25:26 +00001735 >>> isinstance(c, cls.C) # isinstance is false?!?
1736 False
1737
Georg Brandl62eaaf62009-12-19 17:51:41 +00001738The nature of the problem is made clear if you print out the "identity" of the
1739class objects:
Georg Brandld7413152009-10-11 21:25:26 +00001740
Georg Brandl62eaaf62009-12-19 17:51:41 +00001741 >>> hex(id(c.__class__))
1742 '0x7352a0'
1743 >>> hex(id(cls.C))
1744 '0x4198d0'