blob: 1a71c47cb83c666d7362c593cc20751c6695b521 [file] [log] [blame]
Georg Brandld7413152009-10-11 21:25:26 +00001:tocdepth: 2
2
3===============
4Programming FAQ
5===============
6
Georg Brandl44ea77b2013-03-28 13:28:44 +01007.. only:: html
8
9 .. contents::
Georg Brandld7413152009-10-11 21:25:26 +000010
11General Questions
12=================
13
14Is there a source code level debugger with breakpoints, single-stepping, etc.?
15------------------------------------------------------------------------------
16
17Yes.
18
19The pdb module is a simple but adequate console-mode debugger for Python. It is
20part of the standard Python library, and is :mod:`documented in the Library
21Reference Manual <pdb>`. You can also write your own debugger by using the code
22for pdb as an example.
23
24The IDLE interactive development environment, which is part of the standard
25Python distribution (normally available as Tools/scripts/idle), includes a
Georg Brandl5e722f62014-10-29 08:55:14 +010026graphical debugger.
Georg Brandld7413152009-10-11 21:25:26 +000027
28PythonWin is a Python IDE that includes a GUI debugger based on pdb. The
29Pythonwin debugger colors breakpoints and has quite a few cool features such as
30debugging non-Pythonwin programs. Pythonwin is available as part of the `Python
31for Windows Extensions <http://sourceforge.net/projects/pywin32/>`__ project and
32as a part of the ActivePython distribution (see
Georg Brandl77fe77d2014-10-29 09:24:54 +010033http://www.activestate.com/activepython\ ).
Georg Brandld7413152009-10-11 21:25:26 +000034
35`Boa Constructor <http://boa-constructor.sourceforge.net/>`_ is an IDE and GUI
36builder that uses wxWidgets. It offers visual frame creation and manipulation,
37an object inspector, many views on the source like object browsers, inheritance
38hierarchies, doc string generated html documentation, an advanced debugger,
39integrated help, and Zope support.
40
Georg Brandl77fe77d2014-10-29 09:24:54 +010041`Eric <http://eric-ide.python-projects.org/>`_ is an IDE built on PyQt
Georg Brandld7413152009-10-11 21:25:26 +000042and the Scintilla editing component.
43
44Pydb is a version of the standard Python debugger pdb, modified for use with DDD
45(Data Display Debugger), a popular graphical debugger front end. Pydb can be
46found at http://bashdb.sourceforge.net/pydb/ and DDD can be found at
47http://www.gnu.org/software/ddd.
48
49There are a number of commercial Python IDEs that include graphical debuggers.
50They include:
51
52* Wing IDE (http://wingware.com/)
Georg Brandl77fe77d2014-10-29 09:24:54 +010053* Komodo IDE (http://komodoide.com/)
Georg Brandl5e722f62014-10-29 08:55:14 +010054* PyCharm (https://www.jetbrains.com/pycharm/)
Georg Brandld7413152009-10-11 21:25:26 +000055
56
57Is there a tool to help find bugs or perform static analysis?
58-------------------------------------------------------------
59
60Yes.
61
62PyChecker is a static analysis tool that finds bugs in Python source code and
63warns about code complexity and style. You can get PyChecker from
Georg Brandlb7354a62014-10-29 10:57:37 +010064http://pychecker.sourceforge.net/.
Georg Brandld7413152009-10-11 21:25:26 +000065
66`Pylint <http://www.logilab.org/projects/pylint>`_ is another tool that checks
67if a module satisfies a coding standard, and also makes it possible to write
68plug-ins to add a custom feature. In addition to the bug checking that
69PyChecker performs, Pylint offers some additional features such as checking line
70length, whether variable names are well-formed according to your coding
71standard, whether declared interfaces are fully implemented, and more.
Georg Brandl77fe77d2014-10-29 09:24:54 +010072http://docs.pylint.org/ provides a full list of Pylint's features.
Georg Brandld7413152009-10-11 21:25:26 +000073
74
75How can I create a stand-alone binary from a Python script?
76-----------------------------------------------------------
77
78You don't need the ability to compile Python to C code if all you want is a
79stand-alone program that users can download and run without having to install
80the Python distribution first. There are a number of tools that determine the
81set of modules required by a program and bind these modules together with a
82Python binary to produce a single executable.
83
84One is to use the freeze tool, which is included in the Python source tree as
85``Tools/freeze``. It converts Python byte code to C arrays; a C compiler you can
86embed all your modules into a new program, which is then linked with the
87standard Python modules.
88
89It works by scanning your source recursively for import statements (in both
90forms) and looking for the modules in the standard Python path as well as in the
91source directory (for built-in modules). It then turns the bytecode for modules
92written in Python into C code (array initializers that can be turned into code
93objects using the marshal module) and creates a custom-made config file that
94only contains those built-in modules which are actually used in the program. It
95then compiles the generated C code and links it with the rest of the Python
96interpreter to form a self-contained binary which acts exactly like your script.
97
98Obviously, freeze requires a C compiler. There are several other utilities
99which don't. One is Thomas Heller's py2exe (Windows only) at
100
101 http://www.py2exe.org/
102
Georg Brandl77fe77d2014-10-29 09:24:54 +0100103Another tool is Anthony Tuininga's `cx_Freeze <http://cx-freeze.sourceforge.net/>`_.
Georg Brandld7413152009-10-11 21:25:26 +0000104
105
106Are there coding standards or a style guide for Python programs?
107----------------------------------------------------------------
108
109Yes. The coding style required for standard library modules is documented as
110:pep:`8`.
111
112
Georg Brandld7413152009-10-11 21:25:26 +0000113Core Language
114=============
115
R. David Murrayc04a6942009-11-14 22:21:32 +0000116Why am I getting an UnboundLocalError when the variable has a value?
117--------------------------------------------------------------------
Georg Brandld7413152009-10-11 21:25:26 +0000118
R. David Murrayc04a6942009-11-14 22:21:32 +0000119It can be a surprise to get the UnboundLocalError in previously working
120code when it is modified by adding an assignment statement somewhere in
121the body of a function.
Georg Brandld7413152009-10-11 21:25:26 +0000122
R. David Murrayc04a6942009-11-14 22:21:32 +0000123This code:
Georg Brandld7413152009-10-11 21:25:26 +0000124
R. David Murrayc04a6942009-11-14 22:21:32 +0000125 >>> x = 10
126 >>> def bar():
127 ... print(x)
128 >>> bar()
129 10
Georg Brandld7413152009-10-11 21:25:26 +0000130
R. David Murrayc04a6942009-11-14 22:21:32 +0000131works, but this code:
Georg Brandld7413152009-10-11 21:25:26 +0000132
R. David Murrayc04a6942009-11-14 22:21:32 +0000133 >>> x = 10
134 >>> def foo():
135 ... print(x)
136 ... x += 1
Georg Brandld7413152009-10-11 21:25:26 +0000137
R. David Murrayc04a6942009-11-14 22:21:32 +0000138results in an UnboundLocalError:
Georg Brandld7413152009-10-11 21:25:26 +0000139
R. David Murrayc04a6942009-11-14 22:21:32 +0000140 >>> foo()
141 Traceback (most recent call last):
142 ...
143 UnboundLocalError: local variable 'x' referenced before assignment
144
145This is because when you make an assignment to a variable in a scope, that
146variable becomes local to that scope and shadows any similarly named variable
147in the outer scope. Since the last statement in foo assigns a new value to
148``x``, the compiler recognizes it as a local variable. Consequently when the
R. David Murray18163c32009-11-14 22:27:22 +0000149earlier ``print(x)`` attempts to print the uninitialized local variable and
R. David Murrayc04a6942009-11-14 22:21:32 +0000150an error results.
151
152In the example above you can access the outer scope variable by declaring it
153global:
154
155 >>> x = 10
156 >>> def foobar():
157 ... global x
158 ... print(x)
159 ... x += 1
160 >>> foobar()
161 10
162
163This explicit declaration is required in order to remind you that (unlike the
164superficially analogous situation with class and instance variables) you are
165actually modifying the value of the variable in the outer scope:
166
167 >>> print(x)
168 11
169
170You can do a similar thing in a nested scope using the :keyword:`nonlocal`
171keyword:
172
173 >>> def foo():
174 ... x = 10
175 ... def bar():
176 ... nonlocal x
177 ... print(x)
178 ... x += 1
179 ... bar()
180 ... print(x)
181 >>> foo()
182 10
183 11
Georg Brandld7413152009-10-11 21:25:26 +0000184
185
186What are the rules for local and global variables in Python?
187------------------------------------------------------------
188
189In Python, variables that are only referenced inside a function are implicitly
190global. If a variable is assigned a new value anywhere within the function's
191body, it's assumed to be a local. If a variable is ever assigned a new value
192inside the function, the variable is implicitly local, and you need to
193explicitly declare it as 'global'.
194
195Though a bit surprising at first, a moment's consideration explains this. On
196one hand, requiring :keyword:`global` for assigned variables provides a bar
197against unintended side-effects. On the other hand, if ``global`` was required
198for all global references, you'd be using ``global`` all the time. You'd have
Georg Brandlc4a55fc2010-02-06 18:46:57 +0000199to declare as global every reference to a built-in function or to a component of
Georg Brandld7413152009-10-11 21:25:26 +0000200an imported module. This clutter would defeat the usefulness of the ``global``
201declaration for identifying side-effects.
202
203
Ezio Melotticad8b0f2013-01-05 00:50:46 +0200204Why do lambdas defined in a loop with different values all return the same result?
205----------------------------------------------------------------------------------
206
207Assume you use a for loop to define a few different lambdas (or even plain
208functions), e.g.::
209
R David Murrayfdf95032013-06-19 16:58:26 -0400210 >>> squares = []
211 >>> for x in range(5):
212 ... squares.append(lambda: x**2)
Ezio Melotticad8b0f2013-01-05 00:50:46 +0200213
214This gives you a list that contains 5 lambdas that calculate ``x**2``. You
215might expect that, when called, they would return, respectively, ``0``, ``1``,
216``4``, ``9``, and ``16``. However, when you actually try you will see that
217they all return ``16``::
218
219 >>> squares[2]()
220 16
221 >>> squares[4]()
222 16
223
224This happens because ``x`` is not local to the lambdas, but is defined in
225the outer scope, and it is accessed when the lambda is called --- not when it
226is defined. At the end of the loop, the value of ``x`` is ``4``, so all the
227functions now return ``4**2``, i.e. ``16``. You can also verify this by
228changing the value of ``x`` and see how the results of the lambdas change::
229
230 >>> x = 8
231 >>> squares[2]()
232 64
233
234In order to avoid this, you need to save the values in variables local to the
235lambdas, so that they don't rely on the value of the global ``x``::
236
R David Murrayfdf95032013-06-19 16:58:26 -0400237 >>> squares = []
238 >>> for x in range(5):
239 ... squares.append(lambda n=x: n**2)
Ezio Melotticad8b0f2013-01-05 00:50:46 +0200240
241Here, ``n=x`` creates a new variable ``n`` local to the lambda and computed
242when the lambda is defined so that it has the same value that ``x`` had at
243that point in the loop. This means that the value of ``n`` will be ``0``
244in the first lambda, ``1`` in the second, ``2`` in the third, and so on.
245Therefore each lambda will now return the correct result::
246
247 >>> squares[2]()
248 4
249 >>> squares[4]()
250 16
251
252Note that this behaviour is not peculiar to lambdas, but applies to regular
253functions too.
254
255
Georg Brandld7413152009-10-11 21:25:26 +0000256How do I share global variables across modules?
257------------------------------------------------
258
259The canonical way to share information across modules within a single program is
260to create a special module (often called config or cfg). Just import the config
261module in all modules of your application; the module then becomes available as
262a global name. Because there is only one instance of each module, any changes
263made to the module object get reflected everywhere. For example:
264
265config.py::
266
267 x = 0 # Default value of the 'x' configuration setting
268
269mod.py::
270
271 import config
272 config.x = 1
273
274main.py::
275
276 import config
277 import mod
Georg Brandl62eaaf62009-12-19 17:51:41 +0000278 print(config.x)
Georg Brandld7413152009-10-11 21:25:26 +0000279
280Note that using a module is also the basis for implementing the Singleton design
281pattern, for the same reason.
282
283
284What are the "best practices" for using import in a module?
285-----------------------------------------------------------
286
287In general, don't use ``from modulename import *``. Doing so clutters the
Georg Brandla94ad1e2014-10-06 16:02:09 +0200288importer's namespace, and makes it much harder for linters to detect undefined
289names.
Georg Brandld7413152009-10-11 21:25:26 +0000290
291Import modules at the top of a file. Doing so makes it clear what other modules
292your code requires and avoids questions of whether the module name is in scope.
293Using one import per line makes it easy to add and delete module imports, but
294using multiple imports per line uses less screen space.
295
296It's good practice if you import modules in the following order:
297
Georg Brandl62eaaf62009-12-19 17:51:41 +00002981. standard library modules -- e.g. ``sys``, ``os``, ``getopt``, ``re``
Georg Brandld7413152009-10-11 21:25:26 +00002992. third-party library modules (anything installed in Python's site-packages
300 directory) -- e.g. mx.DateTime, ZODB, PIL.Image, etc.
3013. locally-developed modules
302
Georg Brandld7413152009-10-11 21:25:26 +0000303It is sometimes necessary to move imports to a function or class to avoid
304problems with circular imports. Gordon McMillan says:
305
306 Circular imports are fine where both modules use the "import <module>" form
307 of import. They fail when the 2nd module wants to grab a name out of the
308 first ("from module import name") and the import is at the top level. That's
309 because names in the 1st are not yet available, because the first module is
310 busy importing the 2nd.
311
312In this case, if the second module is only used in one function, then the import
313can easily be moved into that function. By the time the import is called, the
314first module will have finished initializing, and the second module can do its
315import.
316
317It may also be necessary to move imports out of the top level of code if some of
318the modules are platform-specific. In that case, it may not even be possible to
319import all of the modules at the top of the file. In this case, importing the
320correct modules in the corresponding platform-specific code is a good option.
321
322Only move imports into a local scope, such as inside a function definition, if
323it's necessary to solve a problem such as avoiding a circular import or are
324trying to reduce the initialization time of a module. This technique is
325especially helpful if many of the imports are unnecessary depending on how the
326program executes. You may also want to move imports into a function if the
327modules are only ever used in that function. Note that loading a module the
328first time may be expensive because of the one time initialization of the
329module, but loading a module multiple times is virtually free, costing only a
330couple of dictionary lookups. Even if the module name has gone out of scope,
331the module is probably available in :data:`sys.modules`.
332
Georg Brandld7413152009-10-11 21:25:26 +0000333
Ezio Melotti898eb822014-07-06 20:53:27 +0300334Why are default values shared between objects?
335----------------------------------------------
336
337This type of bug commonly bites neophyte programmers. Consider this function::
338
339 def foo(mydict={}): # Danger: shared reference to one dict for all calls
340 ... compute something ...
341 mydict[key] = value
342 return mydict
343
344The first time you call this function, ``mydict`` contains a single item. The
345second time, ``mydict`` contains two items because when ``foo()`` begins
346executing, ``mydict`` starts out with an item already in it.
347
348It is often expected that a function call creates new objects for default
349values. This is not what happens. Default values are created exactly once, when
350the function is defined. If that object is changed, like the dictionary in this
351example, subsequent calls to the function will refer to this changed object.
352
353By definition, immutable objects such as numbers, strings, tuples, and ``None``,
354are safe from change. Changes to mutable objects such as dictionaries, lists,
355and class instances can lead to confusion.
356
357Because of this feature, it is good programming practice to not use mutable
358objects as default values. Instead, use ``None`` as the default value and
359inside the function, check if the parameter is ``None`` and create a new
360list/dictionary/whatever if it is. For example, don't write::
361
362 def foo(mydict={}):
363 ...
364
365but::
366
367 def foo(mydict=None):
368 if mydict is None:
369 mydict = {} # create a new dict for local namespace
370
371This feature can be useful. When you have a function that's time-consuming to
372compute, a common technique is to cache the parameters and the resulting value
373of each call to the function, and return the cached value if the same value is
374requested again. This is called "memoizing", and can be implemented like this::
375
376 # Callers will never provide a third parameter for this function.
377 def expensive(arg1, arg2, _cache={}):
378 if (arg1, arg2) in _cache:
379 return _cache[(arg1, arg2)]
380
381 # Calculate the value
382 result = ... expensive computation ...
R David Murray623ae292014-09-28 11:01:11 -0400383 _cache[(arg1, arg2)] = result # Store result in the cache
Ezio Melotti898eb822014-07-06 20:53:27 +0300384 return result
385
386You could use a global variable containing a dictionary instead of the default
387value; it's a matter of taste.
388
389
Georg Brandld7413152009-10-11 21:25:26 +0000390How can I pass optional or keyword parameters from one function to another?
391---------------------------------------------------------------------------
392
393Collect the arguments using the ``*`` and ``**`` specifiers in the function's
394parameter list; this gives you the positional arguments as a tuple and the
395keyword arguments as a dictionary. You can then pass these arguments when
396calling another function by using ``*`` and ``**``::
397
398 def f(x, *args, **kwargs):
399 ...
400 kwargs['width'] = '14.3c'
401 ...
402 g(x, *args, **kwargs)
403
Georg Brandld7413152009-10-11 21:25:26 +0000404
Chris Jerdonekb4309942012-12-25 14:54:44 -0800405.. index::
406 single: argument; difference from parameter
407 single: parameter; difference from argument
408
Chris Jerdonekc2a7fd62012-11-28 02:29:33 -0800409.. _faq-argument-vs-parameter:
410
411What is the difference between arguments and parameters?
412--------------------------------------------------------
413
414:term:`Parameters <parameter>` are defined by the names that appear in a
415function definition, whereas :term:`arguments <argument>` are the values
416actually passed to a function when calling it. Parameters define what types of
417arguments a function can accept. For example, given the function definition::
418
419 def func(foo, bar=None, **kwargs):
420 pass
421
422*foo*, *bar* and *kwargs* are parameters of ``func``. However, when calling
423``func``, for example::
424
425 func(42, bar=314, extra=somevar)
426
427the values ``42``, ``314``, and ``somevar`` are arguments.
428
429
R David Murray623ae292014-09-28 11:01:11 -0400430Why did changing list 'y' also change list 'x'?
431------------------------------------------------
432
433If you wrote code like::
434
435 >>> x = []
436 >>> y = x
437 >>> y.append(10)
438 >>> y
439 [10]
440 >>> x
441 [10]
442
443you might be wondering why appending an element to ``y`` changed ``x`` too.
444
445There are two factors that produce this result:
446
4471) Variables are simply names that refer to objects. Doing ``y = x`` doesn't
448 create a copy of the list -- it creates a new variable ``y`` that refers to
449 the same object ``x`` refers to. This means that there is only one object
450 (the list), and both ``x`` and ``y`` refer to it.
4512) Lists are :term:`mutable`, which means that you can change their content.
452
453After the call to :meth:`~list.append`, the content of the mutable object has
454changed from ``[]`` to ``[10]``. Since both the variables refer to the same
R David Murray12dc0d92014-09-29 10:17:28 -0400455object, using either name accesses the modified value ``[10]``.
R David Murray623ae292014-09-28 11:01:11 -0400456
457If we instead assign an immutable object to ``x``::
458
459 >>> x = 5 # ints are immutable
460 >>> y = x
461 >>> x = x + 1 # 5 can't be mutated, we are creating a new object here
462 >>> x
463 6
464 >>> y
465 5
466
467we can see that in this case ``x`` and ``y`` are not equal anymore. This is
468because integers are :term:`immutable`, and when we do ``x = x + 1`` we are not
469mutating the int ``5`` by incrementing its value; instead, we are creating a
470new object (the int ``6``) and assigning it to ``x`` (that is, changing which
471object ``x`` refers to). After this assignment we have two objects (the ints
472``6`` and ``5``) and two variables that refer to them (``x`` now refers to
473``6`` but ``y`` still refers to ``5``).
474
475Some operations (for example ``y.append(10)`` and ``y.sort()``) mutate the
476object, whereas superficially similar operations (for example ``y = y + [10]``
477and ``sorted(y)``) create a new object. In general in Python (and in all cases
478in the standard library) a method that mutates an object will return ``None``
479to help avoid getting the two types of operations confused. So if you
480mistakenly write ``y.sort()`` thinking it will give you a sorted copy of ``y``,
481you'll instead end up with ``None``, which will likely cause your program to
482generate an easily diagnosed error.
483
484However, there is one class of operations where the same operation sometimes
485has different behaviors with different types: the augmented assignment
486operators. For example, ``+=`` mutates lists but not tuples or ints (``a_list
487+= [1, 2, 3]`` is equivalent to ``a_list.extend([1, 2, 3])`` and mutates
488``a_list``, whereas ``some_tuple += (1, 2, 3)`` and ``some_int += 1`` create
489new objects).
490
491In other words:
492
493* If we have a mutable object (:class:`list`, :class:`dict`, :class:`set`,
494 etc.), we can use some specific operations to mutate it and all the variables
495 that refer to it will see the change.
496* If we have an immutable object (:class:`str`, :class:`int`, :class:`tuple`,
497 etc.), all the variables that refer to it will always see the same value,
498 but operations that transform that value into a new value always return a new
499 object.
500
501If you want to know if two variables refer to the same object or not, you can
502use the :keyword:`is` operator, or the built-in function :func:`id`.
503
504
Georg Brandld7413152009-10-11 21:25:26 +0000505How do I write a function with output parameters (call by reference)?
506---------------------------------------------------------------------
507
508Remember that arguments are passed by assignment in Python. Since assignment
509just creates references to objects, there's no alias between an argument name in
510the caller and callee, and so no call-by-reference per se. You can achieve the
511desired effect in a number of ways.
512
5131) By returning a tuple of the results::
514
515 def func2(a, b):
516 a = 'new-value' # a and b are local names
517 b = b + 1 # assigned to new objects
518 return a, b # return new values
519
520 x, y = 'old-value', 99
521 x, y = func2(x, y)
Georg Brandl62eaaf62009-12-19 17:51:41 +0000522 print(x, y) # output: new-value 100
Georg Brandld7413152009-10-11 21:25:26 +0000523
524 This is almost always the clearest solution.
525
5262) By using global variables. This isn't thread-safe, and is not recommended.
527
5283) By passing a mutable (changeable in-place) object::
529
530 def func1(a):
531 a[0] = 'new-value' # 'a' references a mutable list
532 a[1] = a[1] + 1 # changes a shared object
533
534 args = ['old-value', 99]
535 func1(args)
Georg Brandl62eaaf62009-12-19 17:51:41 +0000536 print(args[0], args[1]) # output: new-value 100
Georg Brandld7413152009-10-11 21:25:26 +0000537
5384) By passing in a dictionary that gets mutated::
539
540 def func3(args):
541 args['a'] = 'new-value' # args is a mutable dictionary
542 args['b'] = args['b'] + 1 # change it in-place
543
544 args = {'a':' old-value', 'b': 99}
545 func3(args)
Georg Brandl62eaaf62009-12-19 17:51:41 +0000546 print(args['a'], args['b'])
Georg Brandld7413152009-10-11 21:25:26 +0000547
5485) Or bundle up values in a class instance::
549
550 class callByRef:
551 def __init__(self, **args):
552 for (key, value) in args.items():
553 setattr(self, key, value)
554
555 def func4(args):
556 args.a = 'new-value' # args is a mutable callByRef
557 args.b = args.b + 1 # change object in-place
558
559 args = callByRef(a='old-value', b=99)
560 func4(args)
Georg Brandl62eaaf62009-12-19 17:51:41 +0000561 print(args.a, args.b)
Georg Brandld7413152009-10-11 21:25:26 +0000562
563
564 There's almost never a good reason to get this complicated.
565
566Your best choice is to return a tuple containing the multiple results.
567
568
569How do you make a higher order function in Python?
570--------------------------------------------------
571
572You have two choices: you can use nested scopes or you can use callable objects.
573For example, suppose you wanted to define ``linear(a,b)`` which returns a
574function ``f(x)`` that computes the value ``a*x+b``. Using nested scopes::
575
576 def linear(a, b):
577 def result(x):
578 return a * x + b
579 return result
580
581Or using a callable object::
582
583 class linear:
584
585 def __init__(self, a, b):
586 self.a, self.b = a, b
587
588 def __call__(self, x):
589 return self.a * x + self.b
590
591In both cases, ::
592
593 taxes = linear(0.3, 2)
594
595gives a callable object where ``taxes(10e6) == 0.3 * 10e6 + 2``.
596
597The callable object approach has the disadvantage that it is a bit slower and
598results in slightly longer code. However, note that a collection of callables
599can share their signature via inheritance::
600
601 class exponential(linear):
602 # __init__ inherited
603 def __call__(self, x):
604 return self.a * (x ** self.b)
605
606Object can encapsulate state for several methods::
607
608 class counter:
609
610 value = 0
611
612 def set(self, x):
613 self.value = x
614
615 def up(self):
616 self.value = self.value + 1
617
618 def down(self):
619 self.value = self.value - 1
620
621 count = counter()
622 inc, dec, reset = count.up, count.down, count.set
623
624Here ``inc()``, ``dec()`` and ``reset()`` act like functions which share the
625same counting variable.
626
627
628How do I copy an object in Python?
629----------------------------------
630
631In general, try :func:`copy.copy` or :func:`copy.deepcopy` for the general case.
632Not all objects can be copied, but most can.
633
634Some objects can be copied more easily. Dictionaries have a :meth:`~dict.copy`
635method::
636
637 newdict = olddict.copy()
638
639Sequences can be copied by slicing::
640
641 new_l = l[:]
642
643
644How can I find the methods or attributes of an object?
645------------------------------------------------------
646
647For an instance x of a user-defined class, ``dir(x)`` returns an alphabetized
648list of the names containing the instance attributes and methods and attributes
649defined by its class.
650
651
652How can my code discover the name of an object?
653-----------------------------------------------
654
655Generally speaking, it can't, because objects don't really have names.
656Essentially, assignment always binds a name to a value; The same is true of
657``def`` and ``class`` statements, but in that case the value is a
658callable. Consider the following code::
659
660 class A:
661 pass
662
663 B = A
664
665 a = B()
666 b = a
Georg Brandl62eaaf62009-12-19 17:51:41 +0000667 print(b)
668 <__main__.A object at 0x16D07CC>
669 print(a)
670 <__main__.A object at 0x16D07CC>
Georg Brandld7413152009-10-11 21:25:26 +0000671
672Arguably the class has a name: even though it is bound to two names and invoked
673through the name B the created instance is still reported as an instance of
674class A. However, it is impossible to say whether the instance's name is a or
675b, since both names are bound to the same value.
676
677Generally speaking it should not be necessary for your code to "know the names"
678of particular values. Unless you are deliberately writing introspective
679programs, this is usually an indication that a change of approach might be
680beneficial.
681
682In comp.lang.python, Fredrik Lundh once gave an excellent analogy in answer to
683this question:
684
685 The same way as you get the name of that cat you found on your porch: the cat
686 (object) itself cannot tell you its name, and it doesn't really care -- so
687 the only way to find out what it's called is to ask all your neighbours
688 (namespaces) if it's their cat (object)...
689
690 ....and don't be surprised if you'll find that it's known by many names, or
691 no name at all!
692
693
694What's up with the comma operator's precedence?
695-----------------------------------------------
696
697Comma is not an operator in Python. Consider this session::
698
699 >>> "a" in "b", "a"
Georg Brandl62eaaf62009-12-19 17:51:41 +0000700 (False, 'a')
Georg Brandld7413152009-10-11 21:25:26 +0000701
702Since the comma is not an operator, but a separator between expressions the
703above is evaluated as if you had entered::
704
R David Murrayfdf95032013-06-19 16:58:26 -0400705 ("a" in "b"), "a"
Georg Brandld7413152009-10-11 21:25:26 +0000706
707not::
708
R David Murrayfdf95032013-06-19 16:58:26 -0400709 "a" in ("b", "a")
Georg Brandld7413152009-10-11 21:25:26 +0000710
711The same is true of the various assignment operators (``=``, ``+=`` etc). They
712are not truly operators but syntactic delimiters in assignment statements.
713
714
715Is there an equivalent of C's "?:" ternary operator?
716----------------------------------------------------
717
Antoine Pitrouc5b266e2011-12-03 22:11:11 +0100718Yes, there is. The syntax is as follows::
Georg Brandld7413152009-10-11 21:25:26 +0000719
720 [on_true] if [expression] else [on_false]
721
722 x, y = 50, 25
Georg Brandld7413152009-10-11 21:25:26 +0000723 small = x if x < y else y
724
Antoine Pitrouc5b266e2011-12-03 22:11:11 +0100725Before this syntax was introduced in Python 2.5, a common idiom was to use
726logical operators::
Georg Brandld7413152009-10-11 21:25:26 +0000727
Antoine Pitrouc5b266e2011-12-03 22:11:11 +0100728 [expression] and [on_true] or [on_false]
Georg Brandld7413152009-10-11 21:25:26 +0000729
Antoine Pitrouc5b266e2011-12-03 22:11:11 +0100730However, this idiom is unsafe, as it can give wrong results when *on_true*
731has a false boolean value. Therefore, it is always better to use
732the ``... if ... else ...`` form.
Georg Brandld7413152009-10-11 21:25:26 +0000733
734
735Is it possible to write obfuscated one-liners in Python?
736--------------------------------------------------------
737
738Yes. Usually this is done by nesting :keyword:`lambda` within
739:keyword:`lambda`. See the following three examples, due to Ulf Bartelt::
740
Georg Brandl62eaaf62009-12-19 17:51:41 +0000741 from functools import reduce
742
Georg Brandld7413152009-10-11 21:25:26 +0000743 # Primes < 1000
Georg Brandl62eaaf62009-12-19 17:51:41 +0000744 print(list(filter(None,map(lambda y:y*reduce(lambda x,y:x*y!=0,
745 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 +0000746
747 # First 10 Fibonacci numbers
Georg Brandl62eaaf62009-12-19 17:51:41 +0000748 print(list(map(lambda x,f=lambda x,f:(f(x-1,f)+f(x-2,f)) if x>1 else 1:
749 f(x,f), range(10))))
Georg Brandld7413152009-10-11 21:25:26 +0000750
751 # Mandelbrot set
Georg Brandl62eaaf62009-12-19 17:51:41 +0000752 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 +0000753 Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,Sy=Sy,L=lambda yc,Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,i=IM,
754 Sx=Sx,Sy=Sy:reduce(lambda x,y:x+y,map(lambda x,xc=Ru,yc=yc,Ru=Ru,Ro=Ro,
755 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
756 >=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(
757 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 +0000758 ))))(-2.1, 0.7, -1.2, 1.2, 30, 80, 24))
Georg Brandld7413152009-10-11 21:25:26 +0000759 # \___ ___/ \___ ___/ | | |__ lines on screen
760 # V V | |______ columns on screen
761 # | | |__________ maximum of "iterations"
762 # | |_________________ range on y axis
763 # |____________________________ range on x axis
764
765Don't try this at home, kids!
766
767
768Numbers and strings
769===================
770
771How do I specify hexadecimal and octal integers?
772------------------------------------------------
773
Georg Brandl62eaaf62009-12-19 17:51:41 +0000774To specify an octal digit, precede the octal value with a zero, and then a lower
775or uppercase "o". For example, to set the variable "a" to the octal value "10"
776(8 in decimal), type::
Georg Brandld7413152009-10-11 21:25:26 +0000777
Georg Brandl62eaaf62009-12-19 17:51:41 +0000778 >>> a = 0o10
Georg Brandld7413152009-10-11 21:25:26 +0000779 >>> a
780 8
781
782Hexadecimal is just as easy. Simply precede the hexadecimal number with a zero,
783and then a lower or uppercase "x". Hexadecimal digits can be specified in lower
784or uppercase. For example, in the Python interpreter::
785
786 >>> a = 0xa5
787 >>> a
788 165
789 >>> b = 0XB2
790 >>> b
791 178
792
793
Georg Brandl62eaaf62009-12-19 17:51:41 +0000794Why does -22 // 10 return -3?
795-----------------------------
Georg Brandld7413152009-10-11 21:25:26 +0000796
797It's primarily driven by the desire that ``i % j`` have the same sign as ``j``.
798If you want that, and also want::
799
Georg Brandl62eaaf62009-12-19 17:51:41 +0000800 i == (i // j) * j + (i % j)
Georg Brandld7413152009-10-11 21:25:26 +0000801
802then integer division has to return the floor. C also requires that identity to
Georg Brandl62eaaf62009-12-19 17:51:41 +0000803hold, and then compilers that truncate ``i // j`` need to make ``i % j`` have
804the same sign as ``i``.
Georg Brandld7413152009-10-11 21:25:26 +0000805
806There are few real use cases for ``i % j`` when ``j`` is negative. When ``j``
807is positive, there are many, and in virtually all of them it's more useful for
808``i % j`` to be ``>= 0``. If the clock says 10 now, what did it say 200 hours
809ago? ``-190 % 12 == 2`` is useful; ``-190 % 12 == -10`` is a bug waiting to
810bite.
811
812
813How do I convert a string to a number?
814--------------------------------------
815
816For integers, use the built-in :func:`int` type constructor, e.g. ``int('144')
817== 144``. Similarly, :func:`float` converts to floating-point,
818e.g. ``float('144') == 144.0``.
819
820By default, these interpret the number as decimal, so that ``int('0144') ==
821144`` and ``int('0x144')`` raises :exc:`ValueError`. ``int(string, base)`` takes
822the base to convert from as a second optional argument, so ``int('0x144', 16) ==
823324``. If the base is specified as 0, the number is interpreted using Python's
Eric V. Smithfc9a4d82014-04-14 07:41:52 -0400824rules: a leading '0o' indicates octal, and '0x' indicates a hex number.
Georg Brandld7413152009-10-11 21:25:26 +0000825
826Do not use the built-in function :func:`eval` if all you need is to convert
827strings to numbers. :func:`eval` will be significantly slower and it presents a
828security risk: someone could pass you a Python expression that might have
829unwanted side effects. For example, someone could pass
830``__import__('os').system("rm -rf $HOME")`` which would erase your home
831directory.
832
833:func:`eval` also has the effect of interpreting numbers as Python expressions,
Georg Brandl62eaaf62009-12-19 17:51:41 +0000834so that e.g. ``eval('09')`` gives a syntax error because Python does not allow
835leading '0' in a decimal number (except '0').
Georg Brandld7413152009-10-11 21:25:26 +0000836
837
838How do I convert a number to a string?
839--------------------------------------
840
841To convert, e.g., the number 144 to the string '144', use the built-in type
842constructor :func:`str`. If you want a hexadecimal or octal representation, use
Georg Brandl62eaaf62009-12-19 17:51:41 +0000843the built-in functions :func:`hex` or :func:`oct`. For fancy formatting, see
844the :ref:`string-formatting` section, e.g. ``"{:04d}".format(144)`` yields
Eric V. Smith04d8a242014-04-14 07:52:53 -0400845``'0144'`` and ``"{:.3f}".format(1.0/3.0)`` yields ``'0.333'``.
Georg Brandld7413152009-10-11 21:25:26 +0000846
847
848How do I modify a string in place?
849----------------------------------
850
Antoine Pitrouc5b266e2011-12-03 22:11:11 +0100851You can't, because strings are immutable. In most situations, you should
852simply construct a new string from the various parts you want to assemble
853it from. However, if you need an object with the ability to modify in-place
854unicode data, try using a :class:`io.StringIO` object or the :mod:`array`
855module::
Georg Brandld7413152009-10-11 21:25:26 +0000856
R David Murrayfdf95032013-06-19 16:58:26 -0400857 >>> import io
Georg Brandld7413152009-10-11 21:25:26 +0000858 >>> s = "Hello, world"
Antoine Pitrouc5b266e2011-12-03 22:11:11 +0100859 >>> sio = io.StringIO(s)
860 >>> sio.getvalue()
861 'Hello, world'
862 >>> sio.seek(7)
863 7
864 >>> sio.write("there!")
865 6
866 >>> sio.getvalue()
Georg Brandld7413152009-10-11 21:25:26 +0000867 'Hello, there!'
868
869 >>> import array
Georg Brandl62eaaf62009-12-19 17:51:41 +0000870 >>> a = array.array('u', s)
871 >>> print(a)
872 array('u', 'Hello, world')
873 >>> a[0] = 'y'
874 >>> print(a)
R David Murrayfdf95032013-06-19 16:58:26 -0400875 array('u', 'yello, world')
Georg Brandl62eaaf62009-12-19 17:51:41 +0000876 >>> a.tounicode()
Georg Brandld7413152009-10-11 21:25:26 +0000877 'yello, world'
878
879
880How do I use strings to call functions/methods?
881-----------------------------------------------
882
883There are various techniques.
884
885* The best is to use a dictionary that maps strings to functions. The primary
886 advantage of this technique is that the strings do not need to match the names
887 of the functions. This is also the primary technique used to emulate a case
888 construct::
889
890 def a():
891 pass
892
893 def b():
894 pass
895
896 dispatch = {'go': a, 'stop': b} # Note lack of parens for funcs
897
898 dispatch[get_input()]() # Note trailing parens to call function
899
900* Use the built-in function :func:`getattr`::
901
902 import foo
903 getattr(foo, 'bar')()
904
905 Note that :func:`getattr` works on any object, including classes, class
906 instances, modules, and so on.
907
908 This is used in several places in the standard library, like this::
909
910 class Foo:
911 def do_foo(self):
912 ...
913
914 def do_bar(self):
915 ...
916
917 f = getattr(foo_instance, 'do_' + opname)
918 f()
919
920
921* Use :func:`locals` or :func:`eval` to resolve the function name::
922
923 def myFunc():
Georg Brandl62eaaf62009-12-19 17:51:41 +0000924 print("hello")
Georg Brandld7413152009-10-11 21:25:26 +0000925
926 fname = "myFunc"
927
928 f = locals()[fname]
929 f()
930
931 f = eval(fname)
932 f()
933
934 Note: Using :func:`eval` is slow and dangerous. If you don't have absolute
935 control over the contents of the string, someone could pass a string that
936 resulted in an arbitrary function being executed.
937
938Is there an equivalent to Perl's chomp() for removing trailing newlines from strings?
939-------------------------------------------------------------------------------------
940
Antoine Pitrouf3520402011-12-03 22:19:55 +0100941You can use ``S.rstrip("\r\n")`` to remove all occurrences of any line
942terminator from the end of the string ``S`` without removing other trailing
943whitespace. If the string ``S`` represents more than one line, with several
944empty lines at the end, the line terminators for all the blank lines will
945be removed::
Georg Brandld7413152009-10-11 21:25:26 +0000946
947 >>> lines = ("line 1 \r\n"
948 ... "\r\n"
949 ... "\r\n")
950 >>> lines.rstrip("\n\r")
Georg Brandl62eaaf62009-12-19 17:51:41 +0000951 'line 1 '
Georg Brandld7413152009-10-11 21:25:26 +0000952
953Since this is typically only desired when reading text one line at a time, using
954``S.rstrip()`` this way works well.
955
Georg Brandld7413152009-10-11 21:25:26 +0000956
957Is there a scanf() or sscanf() equivalent?
958------------------------------------------
959
960Not as such.
961
962For simple input parsing, the easiest approach is usually to split the line into
963whitespace-delimited words using the :meth:`~str.split` method of string objects
964and then convert decimal strings to numeric values using :func:`int` or
965:func:`float`. ``split()`` supports an optional "sep" parameter which is useful
966if the line uses something other than whitespace as a separator.
967
Brian Curtin5a7a52f2010-09-23 13:45:21 +0000968For more complicated input parsing, regular expressions are more powerful
Georg Brandl60203b42010-10-06 10:11:56 +0000969than C's :c:func:`sscanf` and better suited for the task.
Georg Brandld7413152009-10-11 21:25:26 +0000970
971
Georg Brandl62eaaf62009-12-19 17:51:41 +0000972What does 'UnicodeDecodeError' or 'UnicodeEncodeError' error mean?
973-------------------------------------------------------------------
Georg Brandld7413152009-10-11 21:25:26 +0000974
Georg Brandl62eaaf62009-12-19 17:51:41 +0000975See the :ref:`unicode-howto`.
Georg Brandld7413152009-10-11 21:25:26 +0000976
977
Antoine Pitrou432259f2011-12-09 23:10:31 +0100978Performance
979===========
980
981My program is too slow. How do I speed it up?
982---------------------------------------------
983
984That's a tough one, in general. First, here are a list of things to
985remember before diving further:
986
Georg Brandl300a6912012-03-14 22:40:08 +0100987* Performance characteristics vary across Python implementations. This FAQ
Antoine Pitrou432259f2011-12-09 23:10:31 +0100988 focusses on :term:`CPython`.
Georg Brandl300a6912012-03-14 22:40:08 +0100989* Behaviour can vary across operating systems, especially when talking about
Antoine Pitrou432259f2011-12-09 23:10:31 +0100990 I/O or multi-threading.
991* You should always find the hot spots in your program *before* attempting to
992 optimize any code (see the :mod:`profile` module).
993* Writing benchmark scripts will allow you to iterate quickly when searching
994 for improvements (see the :mod:`timeit` module).
995* It is highly recommended to have good code coverage (through unit testing
996 or any other technique) before potentially introducing regressions hidden
997 in sophisticated optimizations.
998
999That being said, there are many tricks to speed up Python code. Here are
1000some general principles which go a long way towards reaching acceptable
1001performance levels:
1002
1003* Making your algorithms faster (or changing to faster ones) can yield
1004 much larger benefits than trying to sprinkle micro-optimization tricks
1005 all over your code.
1006
1007* Use the right data structures. Study documentation for the :ref:`bltin-types`
1008 and the :mod:`collections` module.
1009
1010* When the standard library provides a primitive for doing something, it is
1011 likely (although not guaranteed) to be faster than any alternative you
1012 may come up with. This is doubly true for primitives written in C, such
1013 as builtins and some extension types. For example, be sure to use
1014 either the :meth:`list.sort` built-in method or the related :func:`sorted`
1015 function to do sorting (and see the
Georg Brandle73778c2014-10-29 08:36:35 +01001016 `sorting mini-HOWTO <https://wiki.python.org/moin/HowTo/Sorting>`_ for examples
Antoine Pitrou432259f2011-12-09 23:10:31 +01001017 of moderately advanced usage).
1018
1019* Abstractions tend to create indirections and force the interpreter to work
1020 more. If the levels of indirection outweigh the amount of useful work
1021 done, your program will be slower. You should avoid excessive abstraction,
1022 especially under the form of tiny functions or methods (which are also often
1023 detrimental to readability).
1024
1025If you have reached the limit of what pure Python can allow, there are tools
1026to take you further away. For example, `Cython <http://cython.org>`_ can
1027compile a slightly modified version of Python code into a C extension, and
1028can be used on many different platforms. Cython can take advantage of
1029compilation (and optional type annotations) to make your code significantly
1030faster than when interpreted. If you are confident in your C programming
1031skills, you can also :ref:`write a C extension module <extending-index>`
1032yourself.
1033
1034.. seealso::
1035 The wiki page devoted to `performance tips
Georg Brandle73778c2014-10-29 08:36:35 +01001036 <https://wiki.python.org/moin/PythonSpeed/PerformanceTips>`_.
Antoine Pitrou432259f2011-12-09 23:10:31 +01001037
1038.. _efficient_string_concatenation:
1039
Antoine Pitroufd9ebd42011-11-25 16:33:53 +01001040What is the most efficient way to concatenate many strings together?
1041--------------------------------------------------------------------
1042
1043:class:`str` and :class:`bytes` objects are immutable, therefore concatenating
1044many strings together is inefficient as each concatenation creates a new
1045object. In the general case, the total runtime cost is quadratic in the
1046total string length.
1047
1048To accumulate many :class:`str` objects, the recommended idiom is to place
1049them into a list and call :meth:`str.join` at the end::
1050
1051 chunks = []
1052 for s in my_strings:
1053 chunks.append(s)
1054 result = ''.join(chunks)
1055
1056(another reasonably efficient idiom is to use :class:`io.StringIO`)
1057
1058To accumulate many :class:`bytes` objects, the recommended idiom is to extend
1059a :class:`bytearray` object using in-place concatenation (the ``+=`` operator)::
1060
1061 result = bytearray()
1062 for b in my_bytes_objects:
1063 result += b
1064
1065
Georg Brandld7413152009-10-11 21:25:26 +00001066Sequences (Tuples/Lists)
1067========================
1068
1069How do I convert between tuples and lists?
1070------------------------------------------
1071
1072The type constructor ``tuple(seq)`` converts any sequence (actually, any
1073iterable) into a tuple with the same items in the same order.
1074
1075For example, ``tuple([1, 2, 3])`` yields ``(1, 2, 3)`` and ``tuple('abc')``
1076yields ``('a', 'b', 'c')``. If the argument is a tuple, it does not make a copy
1077but returns the same object, so it is cheap to call :func:`tuple` when you
1078aren't sure that an object is already a tuple.
1079
1080The type constructor ``list(seq)`` converts any sequence or iterable into a list
1081with the same items in the same order. For example, ``list((1, 2, 3))`` yields
1082``[1, 2, 3]`` and ``list('abc')`` yields ``['a', 'b', 'c']``. If the argument
1083is a list, it makes a copy just like ``seq[:]`` would.
1084
1085
1086What's a negative index?
1087------------------------
1088
1089Python sequences are indexed with positive numbers and negative numbers. For
1090positive numbers 0 is the first index 1 is the second index and so forth. For
1091negative indices -1 is the last index and -2 is the penultimate (next to last)
1092index and so forth. Think of ``seq[-n]`` as the same as ``seq[len(seq)-n]``.
1093
1094Using negative indices can be very convenient. For example ``S[:-1]`` is all of
1095the string except for its last character, which is useful for removing the
1096trailing newline from a string.
1097
1098
1099How do I iterate over a sequence in reverse order?
1100--------------------------------------------------
1101
Georg Brandlc4a55fc2010-02-06 18:46:57 +00001102Use the :func:`reversed` built-in function, which is new in Python 2.4::
Georg Brandld7413152009-10-11 21:25:26 +00001103
1104 for x in reversed(sequence):
1105 ... # do something with x...
1106
1107This won't touch your original sequence, but build a new copy with reversed
1108order to iterate over.
1109
1110With Python 2.3, you can use an extended slice syntax::
1111
1112 for x in sequence[::-1]:
1113 ... # do something with x...
1114
1115
1116How do you remove duplicates from a list?
1117-----------------------------------------
1118
1119See the Python Cookbook for a long discussion of many ways to do this:
1120
Georg Brandl77fe77d2014-10-29 09:24:54 +01001121 http://code.activestate.com/recipes/52560/
Georg Brandld7413152009-10-11 21:25:26 +00001122
1123If you don't mind reordering the list, sort it and then scan from the end of the
1124list, deleting duplicates as you go::
1125
Georg Brandl62eaaf62009-12-19 17:51:41 +00001126 if mylist:
1127 mylist.sort()
1128 last = mylist[-1]
1129 for i in range(len(mylist)-2, -1, -1):
1130 if last == mylist[i]:
1131 del mylist[i]
Georg Brandld7413152009-10-11 21:25:26 +00001132 else:
Georg Brandl62eaaf62009-12-19 17:51:41 +00001133 last = mylist[i]
Georg Brandld7413152009-10-11 21:25:26 +00001134
Antoine Pitrouf3520402011-12-03 22:19:55 +01001135If all elements of the list may be used as set keys (i.e. they are all
1136:term:`hashable`) this is often faster ::
Georg Brandld7413152009-10-11 21:25:26 +00001137
Georg Brandl62eaaf62009-12-19 17:51:41 +00001138 mylist = list(set(mylist))
Georg Brandld7413152009-10-11 21:25:26 +00001139
1140This converts the list into a set, thereby removing duplicates, and then back
1141into a list.
1142
1143
1144How do you make an array in Python?
1145-----------------------------------
1146
1147Use a list::
1148
1149 ["this", 1, "is", "an", "array"]
1150
1151Lists are equivalent to C or Pascal arrays in their time complexity; the primary
1152difference is that a Python list can contain objects of many different types.
1153
1154The ``array`` module also provides methods for creating arrays of fixed types
1155with compact representations, but they are slower to index than lists. Also
1156note that the Numeric extensions and others define array-like structures with
1157various characteristics as well.
1158
1159To get Lisp-style linked lists, you can emulate cons cells using tuples::
1160
1161 lisp_list = ("like", ("this", ("example", None) ) )
1162
1163If mutability is desired, you could use lists instead of tuples. Here the
1164analogue of lisp car is ``lisp_list[0]`` and the analogue of cdr is
1165``lisp_list[1]``. Only do this if you're sure you really need to, because it's
1166usually a lot slower than using Python lists.
1167
1168
1169How do I create a multidimensional list?
1170----------------------------------------
1171
1172You probably tried to make a multidimensional array like this::
1173
R David Murrayfdf95032013-06-19 16:58:26 -04001174 >>> A = [[None] * 2] * 3
Georg Brandld7413152009-10-11 21:25:26 +00001175
1176This looks correct if you print it::
1177
1178 >>> A
1179 [[None, None], [None, None], [None, None]]
1180
1181But when you assign a value, it shows up in multiple places:
1182
1183 >>> A[0][0] = 5
1184 >>> A
1185 [[5, None], [5, None], [5, None]]
1186
1187The reason is that replicating a list with ``*`` doesn't create copies, it only
1188creates references to the existing objects. The ``*3`` creates a list
1189containing 3 references to the same list of length two. Changes to one row will
1190show in all rows, which is almost certainly not what you want.
1191
1192The suggested approach is to create a list of the desired length first and then
1193fill in each element with a newly created list::
1194
1195 A = [None] * 3
1196 for i in range(3):
1197 A[i] = [None] * 2
1198
1199This generates a list containing 3 different lists of length two. You can also
1200use a list comprehension::
1201
1202 w, h = 2, 3
1203 A = [[None] * w for i in range(h)]
1204
1205Or, you can use an extension that provides a matrix datatype; `Numeric Python
Ezio Melottic1f58392013-06-09 01:04:21 +03001206<http://www.numpy.org/>`_ is the best known.
Georg Brandld7413152009-10-11 21:25:26 +00001207
1208
1209How do I apply a method to a sequence of objects?
1210-------------------------------------------------
1211
1212Use a list comprehension::
1213
Georg Brandl62eaaf62009-12-19 17:51:41 +00001214 result = [obj.method() for obj in mylist]
Georg Brandld7413152009-10-11 21:25:26 +00001215
Larry Hastings3732ed22014-03-15 21:13:56 -07001216.. _faq-augmented-assignment-tuple-error:
Georg Brandld7413152009-10-11 21:25:26 +00001217
R David Murraybcf06d32013-05-20 10:32:46 -04001218Why does a_tuple[i] += ['item'] raise an exception when the addition works?
1219---------------------------------------------------------------------------
1220
1221This is because of a combination of the fact that augmented assignment
1222operators are *assignment* operators, and the difference between mutable and
1223immutable objects in Python.
1224
1225This discussion applies in general when augmented assignment operators are
1226applied to elements of a tuple that point to mutable objects, but we'll use
1227a ``list`` and ``+=`` as our exemplar.
1228
1229If you wrote::
1230
1231 >>> a_tuple = (1, 2)
1232 >>> a_tuple[0] += 1
1233 Traceback (most recent call last):
1234 ...
1235 TypeError: 'tuple' object does not support item assignment
1236
1237The reason for the exception should be immediately clear: ``1`` is added to the
1238object ``a_tuple[0]`` points to (``1``), producing the result object, ``2``,
1239but when we attempt to assign the result of the computation, ``2``, to element
1240``0`` of the tuple, we get an error because we can't change what an element of
1241a tuple points to.
1242
1243Under the covers, what this augmented assignment statement is doing is
1244approximately this::
1245
R David Murray95ae9922013-05-21 11:44:41 -04001246 >>> result = a_tuple[0] + 1
R David Murraybcf06d32013-05-20 10:32:46 -04001247 >>> a_tuple[0] = result
1248 Traceback (most recent call last):
1249 ...
1250 TypeError: 'tuple' object does not support item assignment
1251
1252It is the assignment part of the operation that produces the error, since a
1253tuple is immutable.
1254
1255When you write something like::
1256
1257 >>> a_tuple = (['foo'], 'bar')
1258 >>> a_tuple[0] += ['item']
1259 Traceback (most recent call last):
1260 ...
1261 TypeError: 'tuple' object does not support item assignment
1262
1263The exception is a bit more surprising, and even more surprising is the fact
1264that even though there was an error, the append worked::
1265
1266 >>> a_tuple[0]
1267 ['foo', 'item']
1268
R David Murray95ae9922013-05-21 11:44:41 -04001269To see why this happens, you need to know that (a) if an object implements an
1270``__iadd__`` magic method, it gets called when the ``+=`` augmented assignment
1271is executed, and its return value is what gets used in the assignment statement;
1272and (b) for lists, ``__iadd__`` is equivalent to calling ``extend`` on the list
1273and returning the list. That's why we say that for lists, ``+=`` is a
1274"shorthand" for ``list.extend``::
R David Murraybcf06d32013-05-20 10:32:46 -04001275
1276 >>> a_list = []
1277 >>> a_list += [1]
1278 >>> a_list
1279 [1]
1280
R David Murray95ae9922013-05-21 11:44:41 -04001281This is equivalent to::
R David Murraybcf06d32013-05-20 10:32:46 -04001282
1283 >>> result = a_list.__iadd__([1])
1284 >>> a_list = result
1285
1286The object pointed to by a_list has been mutated, and the pointer to the
1287mutated object is assigned back to ``a_list``. The end result of the
1288assignment is a no-op, since it is a pointer to the same object that ``a_list``
1289was previously pointing to, but the assignment still happens.
1290
1291Thus, in our tuple example what is happening is equivalent to::
1292
1293 >>> result = a_tuple[0].__iadd__(['item'])
1294 >>> a_tuple[0] = result
1295 Traceback (most recent call last):
1296 ...
1297 TypeError: 'tuple' object does not support item assignment
1298
1299The ``__iadd__`` succeeds, and thus the list is extended, but even though
1300``result`` points to the same object that ``a_tuple[0]`` already points to,
1301that final assignment still results in an error, because tuples are immutable.
1302
1303
Georg Brandld7413152009-10-11 21:25:26 +00001304Dictionaries
1305============
1306
Benjamin Petersonb152e172013-11-26 23:05:25 -06001307How can I get a dictionary to store and display its keys in a consistent order?
1308-------------------------------------------------------------------------------
Georg Brandld7413152009-10-11 21:25:26 +00001309
Benjamin Petersonb152e172013-11-26 23:05:25 -06001310Use :class:`collections.OrderedDict`.
Georg Brandld7413152009-10-11 21:25:26 +00001311
1312I want to do a complicated sort: can you do a Schwartzian Transform in Python?
1313------------------------------------------------------------------------------
1314
1315The technique, attributed to Randal Schwartz of the Perl community, sorts the
1316elements of a list by a metric which maps each element to its "sort value". In
1317Python, just use the ``key`` argument for the ``sort()`` method::
1318
1319 Isorted = L[:]
1320 Isorted.sort(key=lambda s: int(s[10:15]))
1321
1322The ``key`` argument is new in Python 2.4, for older versions this kind of
1323sorting is quite simple to do with list comprehensions. To sort a list of
1324strings by their uppercase values::
1325
Georg Brandl62eaaf62009-12-19 17:51:41 +00001326 tmp1 = [(x.upper(), x) for x in L] # Schwartzian transform
Georg Brandld7413152009-10-11 21:25:26 +00001327 tmp1.sort()
1328 Usorted = [x[1] for x in tmp1]
1329
1330To sort by the integer value of a subfield extending from positions 10-15 in
1331each string::
1332
Georg Brandl62eaaf62009-12-19 17:51:41 +00001333 tmp2 = [(int(s[10:15]), s) for s in L] # Schwartzian transform
Georg Brandld7413152009-10-11 21:25:26 +00001334 tmp2.sort()
1335 Isorted = [x[1] for x in tmp2]
1336
Georg Brandl62eaaf62009-12-19 17:51:41 +00001337For versions prior to 3.0, Isorted may also be computed by ::
Georg Brandld7413152009-10-11 21:25:26 +00001338
1339 def intfield(s):
1340 return int(s[10:15])
1341
1342 def Icmp(s1, s2):
1343 return cmp(intfield(s1), intfield(s2))
1344
1345 Isorted = L[:]
1346 Isorted.sort(Icmp)
1347
1348but since this method calls ``intfield()`` many times for each element of L, it
1349is slower than the Schwartzian Transform.
1350
1351
1352How can I sort one list by values from another list?
1353----------------------------------------------------
1354
Georg Brandl62eaaf62009-12-19 17:51:41 +00001355Merge them into an iterator of tuples, sort the resulting list, and then pick
Georg Brandld7413152009-10-11 21:25:26 +00001356out the element you want. ::
1357
1358 >>> list1 = ["what", "I'm", "sorting", "by"]
1359 >>> list2 = ["something", "else", "to", "sort"]
1360 >>> pairs = zip(list1, list2)
Georg Brandl62eaaf62009-12-19 17:51:41 +00001361 >>> pairs = sorted(pairs)
Georg Brandld7413152009-10-11 21:25:26 +00001362 >>> pairs
Georg Brandl62eaaf62009-12-19 17:51:41 +00001363 [("I'm", 'else'), ('by', 'sort'), ('sorting', 'to'), ('what', 'something')]
1364 >>> result = [x[1] for x in pairs]
Georg Brandld7413152009-10-11 21:25:26 +00001365 >>> result
1366 ['else', 'sort', 'to', 'something']
1367
Georg Brandl62eaaf62009-12-19 17:51:41 +00001368
Georg Brandld7413152009-10-11 21:25:26 +00001369An alternative for the last step is::
1370
Georg Brandl62eaaf62009-12-19 17:51:41 +00001371 >>> result = []
1372 >>> for p in pairs: result.append(p[1])
Georg Brandld7413152009-10-11 21:25:26 +00001373
1374If you find this more legible, you might prefer to use this instead of the final
1375list comprehension. However, it is almost twice as slow for long lists. Why?
1376First, the ``append()`` operation has to reallocate memory, and while it uses
1377some tricks to avoid doing that each time, it still has to do it occasionally,
1378and that costs quite a bit. Second, the expression "result.append" requires an
1379extra attribute lookup, and third, there's a speed reduction from having to make
1380all those function calls.
1381
1382
1383Objects
1384=======
1385
1386What is a class?
1387----------------
1388
1389A class is the particular object type created by executing a class statement.
1390Class objects are used as templates to create instance objects, which embody
1391both the data (attributes) and code (methods) specific to a datatype.
1392
1393A class can be based on one or more other classes, called its base class(es). It
1394then inherits the attributes and methods of its base classes. This allows an
1395object model to be successively refined by inheritance. You might have a
1396generic ``Mailbox`` class that provides basic accessor methods for a mailbox,
1397and subclasses such as ``MboxMailbox``, ``MaildirMailbox``, ``OutlookMailbox``
1398that handle various specific mailbox formats.
1399
1400
1401What is a method?
1402-----------------
1403
1404A method is a function on some object ``x`` that you normally call as
1405``x.name(arguments...)``. Methods are defined as functions inside the class
1406definition::
1407
1408 class C:
1409 def meth (self, arg):
1410 return arg * 2 + self.attribute
1411
1412
1413What is self?
1414-------------
1415
1416Self is merely a conventional name for the first argument of a method. A method
1417defined as ``meth(self, a, b, c)`` should be called as ``x.meth(a, b, c)`` for
1418some instance ``x`` of the class in which the definition occurs; the called
1419method will think it is called as ``meth(x, a, b, c)``.
1420
1421See also :ref:`why-self`.
1422
1423
1424How do I check if an object is an instance of a given class or of a subclass of it?
1425-----------------------------------------------------------------------------------
1426
1427Use the built-in function ``isinstance(obj, cls)``. You can check if an object
1428is an instance of any of a number of classes by providing a tuple instead of a
1429single class, e.g. ``isinstance(obj, (class1, class2, ...))``, and can also
1430check whether an object is one of Python's built-in types, e.g.
Georg Brandl62eaaf62009-12-19 17:51:41 +00001431``isinstance(obj, str)`` or ``isinstance(obj, (int, float, complex))``.
Georg Brandld7413152009-10-11 21:25:26 +00001432
1433Note that most programs do not use :func:`isinstance` on user-defined classes
1434very often. If you are developing the classes yourself, a more proper
1435object-oriented style is to define methods on the classes that encapsulate a
1436particular behaviour, instead of checking the object's class and doing a
1437different thing based on what class it is. For example, if you have a function
1438that does something::
1439
Georg Brandl62eaaf62009-12-19 17:51:41 +00001440 def search(obj):
Georg Brandld7413152009-10-11 21:25:26 +00001441 if isinstance(obj, Mailbox):
1442 # ... code to search a mailbox
1443 elif isinstance(obj, Document):
1444 # ... code to search a document
1445 elif ...
1446
1447A better approach is to define a ``search()`` method on all the classes and just
1448call it::
1449
1450 class Mailbox:
1451 def search(self):
1452 # ... code to search a mailbox
1453
1454 class Document:
1455 def search(self):
1456 # ... code to search a document
1457
1458 obj.search()
1459
1460
1461What is delegation?
1462-------------------
1463
1464Delegation is an object oriented technique (also called a design pattern).
1465Let's say you have an object ``x`` and want to change the behaviour of just one
1466of its methods. You can create a new class that provides a new implementation
1467of the method you're interested in changing and delegates all other methods to
1468the corresponding method of ``x``.
1469
1470Python programmers can easily implement delegation. For example, the following
1471class implements a class that behaves like a file but converts all written data
1472to uppercase::
1473
1474 class UpperOut:
1475
1476 def __init__(self, outfile):
1477 self._outfile = outfile
1478
1479 def write(self, s):
1480 self._outfile.write(s.upper())
1481
1482 def __getattr__(self, name):
1483 return getattr(self._outfile, name)
1484
1485Here the ``UpperOut`` class redefines the ``write()`` method to convert the
1486argument string to uppercase before calling the underlying
1487``self.__outfile.write()`` method. All other methods are delegated to the
1488underlying ``self.__outfile`` object. The delegation is accomplished via the
1489``__getattr__`` method; consult :ref:`the language reference <attribute-access>`
1490for more information about controlling attribute access.
1491
1492Note that for more general cases delegation can get trickier. When attributes
1493must be set as well as retrieved, the class must define a :meth:`__setattr__`
1494method too, and it must do so carefully. The basic implementation of
1495:meth:`__setattr__` is roughly equivalent to the following::
1496
1497 class X:
1498 ...
1499 def __setattr__(self, name, value):
1500 self.__dict__[name] = value
1501 ...
1502
1503Most :meth:`__setattr__` implementations must modify ``self.__dict__`` to store
1504local state for self without causing an infinite recursion.
1505
1506
1507How do I call a method defined in a base class from a derived class that overrides it?
1508--------------------------------------------------------------------------------------
1509
Georg Brandl62eaaf62009-12-19 17:51:41 +00001510Use the built-in :func:`super` function::
Georg Brandld7413152009-10-11 21:25:26 +00001511
1512 class Derived(Base):
1513 def meth (self):
1514 super(Derived, self).meth()
1515
Georg Brandl62eaaf62009-12-19 17:51:41 +00001516For version prior to 3.0, you may be using classic classes: For a class
1517definition such as ``class Derived(Base): ...`` you can call method ``meth()``
1518defined in ``Base`` (or one of ``Base``'s base classes) as ``Base.meth(self,
1519arguments...)``. Here, ``Base.meth`` is an unbound method, so you need to
1520provide the ``self`` argument.
Georg Brandld7413152009-10-11 21:25:26 +00001521
1522
1523How can I organize my code to make it easier to change the base class?
1524----------------------------------------------------------------------
1525
1526You could define an alias for the base class, assign the real base class to it
1527before your class definition, and use the alias throughout your class. Then all
1528you have to change is the value assigned to the alias. Incidentally, this trick
1529is also handy if you want to decide dynamically (e.g. depending on availability
1530of resources) which base class to use. Example::
1531
1532 BaseAlias = <real base class>
1533
1534 class Derived(BaseAlias):
1535 def meth(self):
1536 BaseAlias.meth(self)
1537 ...
1538
1539
1540How do I create static class data and static class methods?
1541-----------------------------------------------------------
1542
Georg Brandl62eaaf62009-12-19 17:51:41 +00001543Both static data and static methods (in the sense of C++ or Java) are supported
1544in Python.
Georg Brandld7413152009-10-11 21:25:26 +00001545
1546For static data, simply define a class attribute. To assign a new value to the
1547attribute, you have to explicitly use the class name in the assignment::
1548
1549 class C:
1550 count = 0 # number of times C.__init__ called
1551
1552 def __init__(self):
1553 C.count = C.count + 1
1554
1555 def getcount(self):
1556 return C.count # or return self.count
1557
1558``c.count`` also refers to ``C.count`` for any ``c`` such that ``isinstance(c,
1559C)`` holds, unless overridden by ``c`` itself or by some class on the base-class
1560search path from ``c.__class__`` back to ``C``.
1561
1562Caution: within a method of C, an assignment like ``self.count = 42`` creates a
Georg Brandl62eaaf62009-12-19 17:51:41 +00001563new and unrelated instance named "count" in ``self``'s own dict. Rebinding of a
1564class-static data name must always specify the class whether inside a method or
1565not::
Georg Brandld7413152009-10-11 21:25:26 +00001566
1567 C.count = 314
1568
Antoine Pitrouf3520402011-12-03 22:19:55 +01001569Static methods are possible::
Georg Brandld7413152009-10-11 21:25:26 +00001570
1571 class C:
1572 @staticmethod
1573 def static(arg1, arg2, arg3):
1574 # No 'self' parameter!
1575 ...
1576
1577However, a far more straightforward way to get the effect of a static method is
1578via a simple module-level function::
1579
1580 def getcount():
1581 return C.count
1582
1583If your code is structured so as to define one class (or tightly related class
1584hierarchy) per module, this supplies the desired encapsulation.
1585
1586
1587How can I overload constructors (or methods) in Python?
1588-------------------------------------------------------
1589
1590This answer actually applies to all methods, but the question usually comes up
1591first in the context of constructors.
1592
1593In C++ you'd write
1594
1595.. code-block:: c
1596
1597 class C {
1598 C() { cout << "No arguments\n"; }
1599 C(int i) { cout << "Argument is " << i << "\n"; }
1600 }
1601
1602In Python you have to write a single constructor that catches all cases using
1603default arguments. For example::
1604
1605 class C:
1606 def __init__(self, i=None):
1607 if i is None:
Georg Brandl62eaaf62009-12-19 17:51:41 +00001608 print("No arguments")
Georg Brandld7413152009-10-11 21:25:26 +00001609 else:
Georg Brandl62eaaf62009-12-19 17:51:41 +00001610 print("Argument is", i)
Georg Brandld7413152009-10-11 21:25:26 +00001611
1612This is not entirely equivalent, but close enough in practice.
1613
1614You could also try a variable-length argument list, e.g. ::
1615
1616 def __init__(self, *args):
1617 ...
1618
1619The same approach works for all method definitions.
1620
1621
1622I try to use __spam and I get an error about _SomeClassName__spam.
1623------------------------------------------------------------------
1624
1625Variable names with double leading underscores are "mangled" to provide a simple
1626but effective way to define class private variables. Any identifier of the form
1627``__spam`` (at least two leading underscores, at most one trailing underscore)
1628is textually replaced with ``_classname__spam``, where ``classname`` is the
1629current class name with any leading underscores stripped.
1630
1631This doesn't guarantee privacy: an outside user can still deliberately access
1632the "_classname__spam" attribute, and private values are visible in the object's
1633``__dict__``. Many Python programmers never bother to use private variable
1634names at all.
1635
1636
1637My class defines __del__ but it is not called when I delete the object.
1638-----------------------------------------------------------------------
1639
1640There are several possible reasons for this.
1641
1642The del statement does not necessarily call :meth:`__del__` -- it simply
1643decrements the object's reference count, and if this reaches zero
1644:meth:`__del__` is called.
1645
1646If your data structures contain circular links (e.g. a tree where each child has
1647a parent reference and each parent has a list of children) the reference counts
1648will never go back to zero. Once in a while Python runs an algorithm to detect
1649such cycles, but the garbage collector might run some time after the last
1650reference to your data structure vanishes, so your :meth:`__del__` method may be
1651called at an inconvenient and random time. This is inconvenient if you're trying
1652to reproduce a problem. Worse, the order in which object's :meth:`__del__`
1653methods are executed is arbitrary. You can run :func:`gc.collect` to force a
1654collection, but there *are* pathological cases where objects will never be
1655collected.
1656
1657Despite the cycle collector, it's still a good idea to define an explicit
1658``close()`` method on objects to be called whenever you're done with them. The
1659``close()`` method can then remove attributes that refer to subobjecs. Don't
1660call :meth:`__del__` directly -- :meth:`__del__` should call ``close()`` and
1661``close()`` should make sure that it can be called more than once for the same
1662object.
1663
1664Another way to avoid cyclical references is to use the :mod:`weakref` module,
1665which allows you to point to objects without incrementing their reference count.
1666Tree data structures, for instance, should use weak references for their parent
1667and sibling references (if they need them!).
1668
Georg Brandl62eaaf62009-12-19 17:51:41 +00001669.. XXX relevant for Python 3?
1670
1671 If the object has ever been a local variable in a function that caught an
1672 expression in an except clause, chances are that a reference to the object
1673 still exists in that function's stack frame as contained in the stack trace.
1674 Normally, calling :func:`sys.exc_clear` will take care of this by clearing
1675 the last recorded exception.
Georg Brandld7413152009-10-11 21:25:26 +00001676
1677Finally, if your :meth:`__del__` method raises an exception, a warning message
1678is printed to :data:`sys.stderr`.
1679
1680
1681How do I get a list of all instances of a given class?
1682------------------------------------------------------
1683
1684Python does not keep track of all instances of a class (or of a built-in type).
1685You can program the class's constructor to keep track of all instances by
1686keeping a list of weak references to each instance.
1687
1688
Georg Brandld8ede4f2013-10-12 18:14:25 +02001689Why does the result of ``id()`` appear to be not unique?
1690--------------------------------------------------------
1691
1692The :func:`id` builtin returns an integer that is guaranteed to be unique during
1693the lifetime of the object. Since in CPython, this is the object's memory
1694address, it happens frequently that after an object is deleted from memory, the
1695next freshly created object is allocated at the same position in memory. This
1696is illustrated by this example:
1697
1698>>> id(1000)
169913901272
1700>>> id(2000)
170113901272
1702
1703The two ids belong to different integer objects that are created before, and
1704deleted immediately after execution of the ``id()`` call. To be sure that
1705objects whose id you want to examine are still alive, create another reference
1706to the object:
1707
1708>>> a = 1000; b = 2000
1709>>> id(a)
171013901272
1711>>> id(b)
171213891296
1713
1714
Georg Brandld7413152009-10-11 21:25:26 +00001715Modules
1716=======
1717
1718How do I create a .pyc file?
1719----------------------------
1720
R David Murrayd913d9d2013-12-13 12:29:29 -05001721When a module is imported for the first time (or when the source file has
1722changed since the current compiled file was created) a ``.pyc`` file containing
1723the compiled code should be created in a ``__pycache__`` subdirectory of the
1724directory containing the ``.py`` file. The ``.pyc`` file will have a
1725filename that starts with the same name as the ``.py`` file, and ends with
1726``.pyc``, with a middle component that depends on the particular ``python``
1727binary that created it. (See :pep:`3147` for details.)
Georg Brandld7413152009-10-11 21:25:26 +00001728
R David Murrayd913d9d2013-12-13 12:29:29 -05001729One reason that a ``.pyc`` file may not be created is a permissions problem
1730with the directory containing the source file, meaning that the ``__pycache__``
1731subdirectory cannot be created. This can happen, for example, if you develop as
1732one user but run as another, such as if you are testing with a web server.
1733
1734Unless the :envvar:`PYTHONDONTWRITEBYTECODE` environment variable is set,
1735creation of a .pyc file is automatic if you're importing a module and Python
1736has the ability (permissions, free space, etc...) to create a ``__pycache__``
1737subdirectory and write the compiled module to that subdirectory.
Georg Brandld7413152009-10-11 21:25:26 +00001738
R David Murrayfdf95032013-06-19 16:58:26 -04001739Running Python on a top level script is not considered an import and no
1740``.pyc`` will be created. For example, if you have a top-level module
R David Murrayd913d9d2013-12-13 12:29:29 -05001741``foo.py`` that imports another module ``xyz.py``, when you run ``foo`` (by
1742typing ``python foo.py`` as a shell command), a ``.pyc`` will be created for
1743``xyz`` because ``xyz`` is imported, but no ``.pyc`` file will be created for
1744``foo`` since ``foo.py`` isn't being imported.
Georg Brandld7413152009-10-11 21:25:26 +00001745
R David Murrayd913d9d2013-12-13 12:29:29 -05001746If you need to create a ``.pyc`` file for ``foo`` -- that is, to create a
1747``.pyc`` file for a module that is not imported -- you can, using the
1748:mod:`py_compile` and :mod:`compileall` modules.
Georg Brandld7413152009-10-11 21:25:26 +00001749
1750The :mod:`py_compile` module can manually compile any module. One way is to use
1751the ``compile()`` function in that module interactively::
1752
1753 >>> import py_compile
R David Murrayfdf95032013-06-19 16:58:26 -04001754 >>> py_compile.compile('foo.py') # doctest: +SKIP
Georg Brandld7413152009-10-11 21:25:26 +00001755
R David Murrayd913d9d2013-12-13 12:29:29 -05001756This will write the ``.pyc`` to a ``__pycache__`` subdirectory in the same
1757location as ``foo.py`` (or you can override that with the optional parameter
1758``cfile``).
Georg Brandld7413152009-10-11 21:25:26 +00001759
1760You can also automatically compile all files in a directory or directories using
1761the :mod:`compileall` module. You can do it from the shell prompt by running
1762``compileall.py`` and providing the path of a directory containing Python files
1763to compile::
1764
1765 python -m compileall .
1766
1767
1768How do I find the current module name?
1769--------------------------------------
1770
1771A module can find out its own module name by looking at the predefined global
1772variable ``__name__``. If this has the value ``'__main__'``, the program is
1773running as a script. Many modules that are usually used by importing them also
1774provide a command-line interface or a self-test, and only execute this code
1775after checking ``__name__``::
1776
1777 def main():
Georg Brandl62eaaf62009-12-19 17:51:41 +00001778 print('Running test...')
Georg Brandld7413152009-10-11 21:25:26 +00001779 ...
1780
1781 if __name__ == '__main__':
1782 main()
1783
1784
1785How can I have modules that mutually import each other?
1786-------------------------------------------------------
1787
1788Suppose you have the following modules:
1789
1790foo.py::
1791
1792 from bar import bar_var
1793 foo_var = 1
1794
1795bar.py::
1796
1797 from foo import foo_var
1798 bar_var = 2
1799
1800The problem is that the interpreter will perform the following steps:
1801
1802* main imports foo
1803* Empty globals for foo are created
1804* foo is compiled and starts executing
1805* foo imports bar
1806* Empty globals for bar are created
1807* bar is compiled and starts executing
1808* bar imports foo (which is a no-op since there already is a module named foo)
1809* bar.foo_var = foo.foo_var
1810
1811The last step fails, because Python isn't done with interpreting ``foo`` yet and
1812the global symbol dictionary for ``foo`` is still empty.
1813
1814The same thing happens when you use ``import foo``, and then try to access
1815``foo.foo_var`` in global code.
1816
1817There are (at least) three possible workarounds for this problem.
1818
1819Guido van Rossum recommends avoiding all uses of ``from <module> import ...``,
1820and placing all code inside functions. Initializations of global variables and
1821class variables should use constants or built-in functions only. This means
1822everything from an imported module is referenced as ``<module>.<name>``.
1823
1824Jim Roskind suggests performing steps in the following order in each module:
1825
1826* exports (globals, functions, and classes that don't need imported base
1827 classes)
1828* ``import`` statements
1829* active code (including globals that are initialized from imported values).
1830
1831van Rossum doesn't like this approach much because the imports appear in a
1832strange place, but it does work.
1833
1834Matthias Urlichs recommends restructuring your code so that the recursive import
1835is not necessary in the first place.
1836
1837These solutions are not mutually exclusive.
1838
1839
1840__import__('x.y.z') returns <module 'x'>; how do I get z?
1841---------------------------------------------------------
1842
Ezio Melottie4aad5a2014-08-04 19:34:29 +03001843Consider using the convenience function :func:`~importlib.import_module` from
1844:mod:`importlib` instead::
Georg Brandld7413152009-10-11 21:25:26 +00001845
Ezio Melottie4aad5a2014-08-04 19:34:29 +03001846 z = importlib.import_module('x.y.z')
Georg Brandld7413152009-10-11 21:25:26 +00001847
1848
1849When I edit an imported module and reimport it, the changes don't show up. Why does this happen?
1850-------------------------------------------------------------------------------------------------
1851
1852For reasons of efficiency as well as consistency, Python only reads the module
1853file on the first time a module is imported. If it didn't, in a program
1854consisting of many modules where each one imports the same basic module, the
Brett Cannon4f422e32013-06-14 22:49:00 -04001855basic module would be parsed and re-parsed many times. To force re-reading of a
Georg Brandld7413152009-10-11 21:25:26 +00001856changed module, do this::
1857
Brett Cannon4f422e32013-06-14 22:49:00 -04001858 import importlib
Georg Brandld7413152009-10-11 21:25:26 +00001859 import modname
Brett Cannon4f422e32013-06-14 22:49:00 -04001860 importlib.reload(modname)
Georg Brandld7413152009-10-11 21:25:26 +00001861
1862Warning: this technique is not 100% fool-proof. In particular, modules
1863containing statements like ::
1864
1865 from modname import some_objects
1866
1867will continue to work with the old version of the imported objects. If the
1868module contains class definitions, existing class instances will *not* be
1869updated to use the new class definition. This can result in the following
1870paradoxical behaviour:
1871
Brett Cannon4f422e32013-06-14 22:49:00 -04001872 >>> import importlib
Georg Brandld7413152009-10-11 21:25:26 +00001873 >>> import cls
1874 >>> c = cls.C() # Create an instance of C
Brett Cannon4f422e32013-06-14 22:49:00 -04001875 >>> importlib.reload(cls)
Georg Brandl62eaaf62009-12-19 17:51:41 +00001876 <module 'cls' from 'cls.py'>
Georg Brandld7413152009-10-11 21:25:26 +00001877 >>> isinstance(c, cls.C) # isinstance is false?!?
1878 False
1879
Georg Brandl62eaaf62009-12-19 17:51:41 +00001880The nature of the problem is made clear if you print out the "identity" of the
1881class objects:
Georg Brandld7413152009-10-11 21:25:26 +00001882
Georg Brandl62eaaf62009-12-19 17:51:41 +00001883 >>> hex(id(c.__class__))
1884 '0x7352a0'
1885 >>> hex(id(cls.C))
1886 '0x4198d0'