blob: 31614189a62d2ceb723e445045c776d948259695 [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
Serhiy Storchaka6dff0202016-05-07 10:49:07 +030031for Windows Extensions <https://sourceforge.net/projects/pywin32/>`__ project and
Georg Brandld7413152009-10-11 21:25:26 +000032as a part of the ActivePython distribution (see
Serhiy Storchaka6dff0202016-05-07 10:49:07 +030033https://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
Serhiy Storchaka6dff0202016-05-07 10:49:07 +030047https://www.gnu.org/software/ddd.
Georg Brandld7413152009-10-11 21:25:26 +000048
49There are a number of commercial Python IDEs that include graphical debuggers.
50They include:
51
Serhiy Storchaka6dff0202016-05-07 10:49:07 +030052* Wing IDE (https://wingware.com/)
53* Komodo IDE (https://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
Serhiy Storchaka6dff0202016-05-07 10:49:07 +030066`Pylint <https://www.pylint.org/>`_ is another tool that checks
Georg Brandld7413152009-10-11 21:25:26 +000067if 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.
Serhiy Storchaka6dff0202016-05-07 10:49:07 +030072https://docs.pylint.org/ provides a full list of Pylint's features.
Georg Brandld7413152009-10-11 21:25:26 +000073
Andrés Delfinoa3782542018-09-11 02:12:41 -030074Static type checkers such as `Mypy <http://mypy-lang.org/>`_,
75`Pyre <https://pyre-check.org/>`_, and
76`Pytype <https://github.com/google/pytype>`_ can check type hints in Python
77source code.
78
Georg Brandld7413152009-10-11 21:25:26 +000079
80How can I create a stand-alone binary from a Python script?
81-----------------------------------------------------------
82
83You don't need the ability to compile Python to C code if all you want is a
84stand-alone program that users can download and run without having to install
85the Python distribution first. There are a number of tools that determine the
86set of modules required by a program and bind these modules together with a
87Python binary to produce a single executable.
88
89One is to use the freeze tool, which is included in the Python source tree as
90``Tools/freeze``. It converts Python byte code to C arrays; a C compiler you can
91embed all your modules into a new program, which is then linked with the
92standard Python modules.
93
94It works by scanning your source recursively for import statements (in both
95forms) and looking for the modules in the standard Python path as well as in the
96source directory (for built-in modules). It then turns the bytecode for modules
97written in Python into C code (array initializers that can be turned into code
98objects using the marshal module) and creates a custom-made config file that
99only contains those built-in modules which are actually used in the program. It
100then compiles the generated C code and links it with the rest of the Python
101interpreter to form a self-contained binary which acts exactly like your script.
102
103Obviously, freeze requires a C compiler. There are several other utilities
104which don't. One is Thomas Heller's py2exe (Windows only) at
105
106 http://www.py2exe.org/
107
Sanyam Khurana1b4587a2017-12-06 22:09:33 +0530108Another tool is Anthony Tuininga's `cx_Freeze <https://anthony-tuininga.github.io/cx_Freeze/>`_.
Georg Brandld7413152009-10-11 21:25:26 +0000109
110
111Are there coding standards or a style guide for Python programs?
112----------------------------------------------------------------
113
114Yes. The coding style required for standard library modules is documented as
115:pep:`8`.
116
117
Georg Brandld7413152009-10-11 21:25:26 +0000118Core Language
119=============
120
R. David Murrayc04a6942009-11-14 22:21:32 +0000121Why am I getting an UnboundLocalError when the variable has a value?
122--------------------------------------------------------------------
Georg Brandld7413152009-10-11 21:25:26 +0000123
R. David Murrayc04a6942009-11-14 22:21:32 +0000124It can be a surprise to get the UnboundLocalError in previously working
125code when it is modified by adding an assignment statement somewhere in
126the body of a function.
Georg Brandld7413152009-10-11 21:25:26 +0000127
R. David Murrayc04a6942009-11-14 22:21:32 +0000128This code:
Georg Brandld7413152009-10-11 21:25:26 +0000129
R. David Murrayc04a6942009-11-14 22:21:32 +0000130 >>> x = 10
131 >>> def bar():
132 ... print(x)
133 >>> bar()
134 10
Georg Brandld7413152009-10-11 21:25:26 +0000135
R. David Murrayc04a6942009-11-14 22:21:32 +0000136works, but this code:
Georg Brandld7413152009-10-11 21:25:26 +0000137
R. David Murrayc04a6942009-11-14 22:21:32 +0000138 >>> x = 10
139 >>> def foo():
140 ... print(x)
141 ... x += 1
Georg Brandld7413152009-10-11 21:25:26 +0000142
R. David Murrayc04a6942009-11-14 22:21:32 +0000143results in an UnboundLocalError:
Georg Brandld7413152009-10-11 21:25:26 +0000144
R. David Murrayc04a6942009-11-14 22:21:32 +0000145 >>> foo()
146 Traceback (most recent call last):
147 ...
148 UnboundLocalError: local variable 'x' referenced before assignment
149
150This is because when you make an assignment to a variable in a scope, that
151variable becomes local to that scope and shadows any similarly named variable
152in the outer scope. Since the last statement in foo assigns a new value to
153``x``, the compiler recognizes it as a local variable. Consequently when the
R. David Murray18163c32009-11-14 22:27:22 +0000154earlier ``print(x)`` attempts to print the uninitialized local variable and
R. David Murrayc04a6942009-11-14 22:21:32 +0000155an error results.
156
157In the example above you can access the outer scope variable by declaring it
158global:
159
160 >>> x = 10
161 >>> def foobar():
162 ... global x
163 ... print(x)
164 ... x += 1
165 >>> foobar()
166 10
167
168This explicit declaration is required in order to remind you that (unlike the
169superficially analogous situation with class and instance variables) you are
170actually modifying the value of the variable in the outer scope:
171
172 >>> print(x)
173 11
174
175You can do a similar thing in a nested scope using the :keyword:`nonlocal`
176keyword:
177
178 >>> def foo():
179 ... x = 10
180 ... def bar():
181 ... nonlocal x
182 ... print(x)
183 ... x += 1
184 ... bar()
185 ... print(x)
186 >>> foo()
187 10
188 11
Georg Brandld7413152009-10-11 21:25:26 +0000189
190
191What are the rules for local and global variables in Python?
192------------------------------------------------------------
193
194In Python, variables that are only referenced inside a function are implicitly
Robert Collinsbd4dd542015-07-30 06:14:32 +1200195global. If a variable is assigned a value anywhere within the function's body,
196it's assumed to be a local unless explicitly declared as global.
Georg Brandld7413152009-10-11 21:25:26 +0000197
198Though a bit surprising at first, a moment's consideration explains this. On
199one hand, requiring :keyword:`global` for assigned variables provides a bar
200against unintended side-effects. On the other hand, if ``global`` was required
201for all global references, you'd be using ``global`` all the time. You'd have
Georg Brandlc4a55fc2010-02-06 18:46:57 +0000202to declare as global every reference to a built-in function or to a component of
Georg Brandld7413152009-10-11 21:25:26 +0000203an imported module. This clutter would defeat the usefulness of the ``global``
204declaration for identifying side-effects.
205
206
Ezio Melotticad8b0f2013-01-05 00:50:46 +0200207Why do lambdas defined in a loop with different values all return the same result?
208----------------------------------------------------------------------------------
209
210Assume you use a for loop to define a few different lambdas (or even plain
211functions), e.g.::
212
R David Murrayfdf95032013-06-19 16:58:26 -0400213 >>> squares = []
214 >>> for x in range(5):
Serhiy Storchakadba90392016-05-10 12:01:23 +0300215 ... squares.append(lambda: x**2)
Ezio Melotticad8b0f2013-01-05 00:50:46 +0200216
217This gives you a list that contains 5 lambdas that calculate ``x**2``. You
218might expect that, when called, they would return, respectively, ``0``, ``1``,
219``4``, ``9``, and ``16``. However, when you actually try you will see that
220they all return ``16``::
221
222 >>> squares[2]()
223 16
224 >>> squares[4]()
225 16
226
227This happens because ``x`` is not local to the lambdas, but is defined in
228the outer scope, and it is accessed when the lambda is called --- not when it
229is defined. At the end of the loop, the value of ``x`` is ``4``, so all the
230functions now return ``4**2``, i.e. ``16``. You can also verify this by
231changing the value of ``x`` and see how the results of the lambdas change::
232
233 >>> x = 8
234 >>> squares[2]()
235 64
236
237In order to avoid this, you need to save the values in variables local to the
238lambdas, so that they don't rely on the value of the global ``x``::
239
R David Murrayfdf95032013-06-19 16:58:26 -0400240 >>> squares = []
241 >>> for x in range(5):
Serhiy Storchakadba90392016-05-10 12:01:23 +0300242 ... squares.append(lambda n=x: n**2)
Ezio Melotticad8b0f2013-01-05 00:50:46 +0200243
244Here, ``n=x`` creates a new variable ``n`` local to the lambda and computed
245when the lambda is defined so that it has the same value that ``x`` had at
246that point in the loop. This means that the value of ``n`` will be ``0``
247in the first lambda, ``1`` in the second, ``2`` in the third, and so on.
248Therefore each lambda will now return the correct result::
249
250 >>> squares[2]()
251 4
252 >>> squares[4]()
253 16
254
255Note that this behaviour is not peculiar to lambdas, but applies to regular
256functions too.
257
258
Georg Brandld7413152009-10-11 21:25:26 +0000259How do I share global variables across modules?
260------------------------------------------------
261
262The canonical way to share information across modules within a single program is
263to create a special module (often called config or cfg). Just import the config
264module in all modules of your application; the module then becomes available as
265a global name. Because there is only one instance of each module, any changes
266made to the module object get reflected everywhere. For example:
267
268config.py::
269
270 x = 0 # Default value of the 'x' configuration setting
271
272mod.py::
273
274 import config
275 config.x = 1
276
277main.py::
278
279 import config
280 import mod
Georg Brandl62eaaf62009-12-19 17:51:41 +0000281 print(config.x)
Georg Brandld7413152009-10-11 21:25:26 +0000282
283Note that using a module is also the basis for implementing the Singleton design
284pattern, for the same reason.
285
286
287What are the "best practices" for using import in a module?
288-----------------------------------------------------------
289
290In general, don't use ``from modulename import *``. Doing so clutters the
Georg Brandla94ad1e2014-10-06 16:02:09 +0200291importer's namespace, and makes it much harder for linters to detect undefined
292names.
Georg Brandld7413152009-10-11 21:25:26 +0000293
294Import modules at the top of a file. Doing so makes it clear what other modules
295your code requires and avoids questions of whether the module name is in scope.
296Using one import per line makes it easy to add and delete module imports, but
297using multiple imports per line uses less screen space.
298
299It's good practice if you import modules in the following order:
300
Georg Brandl62eaaf62009-12-19 17:51:41 +00003011. standard library modules -- e.g. ``sys``, ``os``, ``getopt``, ``re``
Georg Brandld7413152009-10-11 21:25:26 +00003022. third-party library modules (anything installed in Python's site-packages
303 directory) -- e.g. mx.DateTime, ZODB, PIL.Image, etc.
3043. locally-developed modules
305
Georg Brandld7413152009-10-11 21:25:26 +0000306It is sometimes necessary to move imports to a function or class to avoid
307problems with circular imports. Gordon McMillan says:
308
309 Circular imports are fine where both modules use the "import <module>" form
310 of import. They fail when the 2nd module wants to grab a name out of the
311 first ("from module import name") and the import is at the top level. That's
312 because names in the 1st are not yet available, because the first module is
313 busy importing the 2nd.
314
315In this case, if the second module is only used in one function, then the import
316can easily be moved into that function. By the time the import is called, the
317first module will have finished initializing, and the second module can do its
318import.
319
320It may also be necessary to move imports out of the top level of code if some of
321the modules are platform-specific. In that case, it may not even be possible to
322import all of the modules at the top of the file. In this case, importing the
323correct modules in the corresponding platform-specific code is a good option.
324
325Only move imports into a local scope, such as inside a function definition, if
326it's necessary to solve a problem such as avoiding a circular import or are
327trying to reduce the initialization time of a module. This technique is
328especially helpful if many of the imports are unnecessary depending on how the
329program executes. You may also want to move imports into a function if the
330modules are only ever used in that function. Note that loading a module the
331first time may be expensive because of the one time initialization of the
332module, but loading a module multiple times is virtually free, costing only a
333couple of dictionary lookups. Even if the module name has gone out of scope,
334the module is probably available in :data:`sys.modules`.
335
Georg Brandld7413152009-10-11 21:25:26 +0000336
Ezio Melotti898eb822014-07-06 20:53:27 +0300337Why are default values shared between objects?
338----------------------------------------------
339
340This type of bug commonly bites neophyte programmers. Consider this function::
341
342 def foo(mydict={}): # Danger: shared reference to one dict for all calls
343 ... compute something ...
344 mydict[key] = value
345 return mydict
346
347The first time you call this function, ``mydict`` contains a single item. The
348second time, ``mydict`` contains two items because when ``foo()`` begins
349executing, ``mydict`` starts out with an item already in it.
350
351It is often expected that a function call creates new objects for default
352values. This is not what happens. Default values are created exactly once, when
353the function is defined. If that object is changed, like the dictionary in this
354example, subsequent calls to the function will refer to this changed object.
355
356By definition, immutable objects such as numbers, strings, tuples, and ``None``,
357are safe from change. Changes to mutable objects such as dictionaries, lists,
358and class instances can lead to confusion.
359
360Because of this feature, it is good programming practice to not use mutable
361objects as default values. Instead, use ``None`` as the default value and
362inside the function, check if the parameter is ``None`` and create a new
363list/dictionary/whatever if it is. For example, don't write::
364
365 def foo(mydict={}):
366 ...
367
368but::
369
370 def foo(mydict=None):
371 if mydict is None:
372 mydict = {} # create a new dict for local namespace
373
374This feature can be useful. When you have a function that's time-consuming to
375compute, a common technique is to cache the parameters and the resulting value
376of each call to the function, and return the cached value if the same value is
377requested again. This is called "memoizing", and can be implemented like this::
378
Noah Haasis2707e412018-06-16 05:29:11 +0200379 # Callers can only provide two parameters and optionally pass _cache by keyword
380 def expensive(arg1, arg2, *, _cache={}):
Ezio Melotti898eb822014-07-06 20:53:27 +0300381 if (arg1, arg2) in _cache:
382 return _cache[(arg1, arg2)]
383
384 # Calculate the value
385 result = ... expensive computation ...
R David Murray623ae292014-09-28 11:01:11 -0400386 _cache[(arg1, arg2)] = result # Store result in the cache
Ezio Melotti898eb822014-07-06 20:53:27 +0300387 return result
388
389You could use a global variable containing a dictionary instead of the default
390value; it's a matter of taste.
391
392
Georg Brandld7413152009-10-11 21:25:26 +0000393How can I pass optional or keyword parameters from one function to another?
394---------------------------------------------------------------------------
395
396Collect the arguments using the ``*`` and ``**`` specifiers in the function's
397parameter list; this gives you the positional arguments as a tuple and the
398keyword arguments as a dictionary. You can then pass these arguments when
399calling another function by using ``*`` and ``**``::
400
401 def f(x, *args, **kwargs):
402 ...
403 kwargs['width'] = '14.3c'
404 ...
405 g(x, *args, **kwargs)
406
Georg Brandld7413152009-10-11 21:25:26 +0000407
Chris Jerdonekb4309942012-12-25 14:54:44 -0800408.. index::
409 single: argument; difference from parameter
410 single: parameter; difference from argument
411
Chris Jerdonekc2a7fd62012-11-28 02:29:33 -0800412.. _faq-argument-vs-parameter:
413
414What is the difference between arguments and parameters?
415--------------------------------------------------------
416
417:term:`Parameters <parameter>` are defined by the names that appear in a
418function definition, whereas :term:`arguments <argument>` are the values
419actually passed to a function when calling it. Parameters define what types of
420arguments a function can accept. For example, given the function definition::
421
422 def func(foo, bar=None, **kwargs):
423 pass
424
425*foo*, *bar* and *kwargs* are parameters of ``func``. However, when calling
426``func``, for example::
427
428 func(42, bar=314, extra=somevar)
429
430the values ``42``, ``314``, and ``somevar`` are arguments.
431
432
R David Murray623ae292014-09-28 11:01:11 -0400433Why did changing list 'y' also change list 'x'?
434------------------------------------------------
435
436If you wrote code like::
437
438 >>> x = []
439 >>> y = x
440 >>> y.append(10)
441 >>> y
442 [10]
443 >>> x
444 [10]
445
446you might be wondering why appending an element to ``y`` changed ``x`` too.
447
448There are two factors that produce this result:
449
4501) Variables are simply names that refer to objects. Doing ``y = x`` doesn't
451 create a copy of the list -- it creates a new variable ``y`` that refers to
452 the same object ``x`` refers to. This means that there is only one object
453 (the list), and both ``x`` and ``y`` refer to it.
4542) Lists are :term:`mutable`, which means that you can change their content.
455
456After the call to :meth:`~list.append`, the content of the mutable object has
457changed from ``[]`` to ``[10]``. Since both the variables refer to the same
R David Murray12dc0d92014-09-29 10:17:28 -0400458object, using either name accesses the modified value ``[10]``.
R David Murray623ae292014-09-28 11:01:11 -0400459
460If we instead assign an immutable object to ``x``::
461
462 >>> x = 5 # ints are immutable
463 >>> y = x
464 >>> x = x + 1 # 5 can't be mutated, we are creating a new object here
465 >>> x
466 6
467 >>> y
468 5
469
470we can see that in this case ``x`` and ``y`` are not equal anymore. This is
471because integers are :term:`immutable`, and when we do ``x = x + 1`` we are not
472mutating the int ``5`` by incrementing its value; instead, we are creating a
473new object (the int ``6``) and assigning it to ``x`` (that is, changing which
474object ``x`` refers to). After this assignment we have two objects (the ints
475``6`` and ``5``) and two variables that refer to them (``x`` now refers to
476``6`` but ``y`` still refers to ``5``).
477
478Some operations (for example ``y.append(10)`` and ``y.sort()``) mutate the
479object, whereas superficially similar operations (for example ``y = y + [10]``
480and ``sorted(y)``) create a new object. In general in Python (and in all cases
481in the standard library) a method that mutates an object will return ``None``
482to help avoid getting the two types of operations confused. So if you
483mistakenly write ``y.sort()`` thinking it will give you a sorted copy of ``y``,
484you'll instead end up with ``None``, which will likely cause your program to
485generate an easily diagnosed error.
486
487However, there is one class of operations where the same operation sometimes
488has different behaviors with different types: the augmented assignment
489operators. For example, ``+=`` mutates lists but not tuples or ints (``a_list
490+= [1, 2, 3]`` is equivalent to ``a_list.extend([1, 2, 3])`` and mutates
491``a_list``, whereas ``some_tuple += (1, 2, 3)`` and ``some_int += 1`` create
492new objects).
493
494In other words:
495
496* If we have a mutable object (:class:`list`, :class:`dict`, :class:`set`,
497 etc.), we can use some specific operations to mutate it and all the variables
498 that refer to it will see the change.
499* If we have an immutable object (:class:`str`, :class:`int`, :class:`tuple`,
500 etc.), all the variables that refer to it will always see the same value,
501 but operations that transform that value into a new value always return a new
502 object.
503
504If you want to know if two variables refer to the same object or not, you can
505use the :keyword:`is` operator, or the built-in function :func:`id`.
506
507
Georg Brandld7413152009-10-11 21:25:26 +0000508How do I write a function with output parameters (call by reference)?
509---------------------------------------------------------------------
510
511Remember that arguments are passed by assignment in Python. Since assignment
512just creates references to objects, there's no alias between an argument name in
513the caller and callee, and so no call-by-reference per se. You can achieve the
514desired effect in a number of ways.
515
5161) By returning a tuple of the results::
517
518 def func2(a, b):
519 a = 'new-value' # a and b are local names
520 b = b + 1 # assigned to new objects
521 return a, b # return new values
522
523 x, y = 'old-value', 99
524 x, y = func2(x, y)
Georg Brandl62eaaf62009-12-19 17:51:41 +0000525 print(x, y) # output: new-value 100
Georg Brandld7413152009-10-11 21:25:26 +0000526
527 This is almost always the clearest solution.
528
5292) By using global variables. This isn't thread-safe, and is not recommended.
530
5313) By passing a mutable (changeable in-place) object::
532
533 def func1(a):
534 a[0] = 'new-value' # 'a' references a mutable list
535 a[1] = a[1] + 1 # changes a shared object
536
537 args = ['old-value', 99]
538 func1(args)
Georg Brandl62eaaf62009-12-19 17:51:41 +0000539 print(args[0], args[1]) # output: new-value 100
Georg Brandld7413152009-10-11 21:25:26 +0000540
5414) By passing in a dictionary that gets mutated::
542
543 def func3(args):
544 args['a'] = 'new-value' # args is a mutable dictionary
545 args['b'] = args['b'] + 1 # change it in-place
546
Serhiy Storchakadba90392016-05-10 12:01:23 +0300547 args = {'a': 'old-value', 'b': 99}
Georg Brandld7413152009-10-11 21:25:26 +0000548 func3(args)
Georg Brandl62eaaf62009-12-19 17:51:41 +0000549 print(args['a'], args['b'])
Georg Brandld7413152009-10-11 21:25:26 +0000550
5515) Or bundle up values in a class instance::
552
553 class callByRef:
554 def __init__(self, **args):
555 for (key, value) in args.items():
556 setattr(self, key, value)
557
558 def func4(args):
559 args.a = 'new-value' # args is a mutable callByRef
560 args.b = args.b + 1 # change object in-place
561
562 args = callByRef(a='old-value', b=99)
563 func4(args)
Georg Brandl62eaaf62009-12-19 17:51:41 +0000564 print(args.a, args.b)
Georg Brandld7413152009-10-11 21:25:26 +0000565
566
567 There's almost never a good reason to get this complicated.
568
569Your best choice is to return a tuple containing the multiple results.
570
571
572How do you make a higher order function in Python?
573--------------------------------------------------
574
575You have two choices: you can use nested scopes or you can use callable objects.
576For example, suppose you wanted to define ``linear(a,b)`` which returns a
577function ``f(x)`` that computes the value ``a*x+b``. Using nested scopes::
578
579 def linear(a, b):
580 def result(x):
581 return a * x + b
582 return result
583
584Or using a callable object::
585
586 class linear:
587
588 def __init__(self, a, b):
589 self.a, self.b = a, b
590
591 def __call__(self, x):
592 return self.a * x + self.b
593
594In both cases, ::
595
596 taxes = linear(0.3, 2)
597
598gives a callable object where ``taxes(10e6) == 0.3 * 10e6 + 2``.
599
600The callable object approach has the disadvantage that it is a bit slower and
601results in slightly longer code. However, note that a collection of callables
602can share their signature via inheritance::
603
604 class exponential(linear):
605 # __init__ inherited
606 def __call__(self, x):
607 return self.a * (x ** self.b)
608
609Object can encapsulate state for several methods::
610
611 class counter:
612
613 value = 0
614
615 def set(self, x):
616 self.value = x
617
618 def up(self):
619 self.value = self.value + 1
620
621 def down(self):
622 self.value = self.value - 1
623
624 count = counter()
625 inc, dec, reset = count.up, count.down, count.set
626
627Here ``inc()``, ``dec()`` and ``reset()`` act like functions which share the
628same counting variable.
629
630
631How do I copy an object in Python?
632----------------------------------
633
634In general, try :func:`copy.copy` or :func:`copy.deepcopy` for the general case.
635Not all objects can be copied, but most can.
636
637Some objects can be copied more easily. Dictionaries have a :meth:`~dict.copy`
638method::
639
640 newdict = olddict.copy()
641
642Sequences can be copied by slicing::
643
644 new_l = l[:]
645
646
647How can I find the methods or attributes of an object?
648------------------------------------------------------
649
650For an instance x of a user-defined class, ``dir(x)`` returns an alphabetized
651list of the names containing the instance attributes and methods and attributes
652defined by its class.
653
654
655How can my code discover the name of an object?
656-----------------------------------------------
657
658Generally speaking, it can't, because objects don't really have names.
659Essentially, assignment always binds a name to a value; The same is true of
660``def`` and ``class`` statements, but in that case the value is a
661callable. Consider the following code::
662
Serhiy Storchakadba90392016-05-10 12:01:23 +0300663 >>> class A:
664 ... pass
665 ...
666 >>> B = A
667 >>> a = B()
668 >>> b = a
669 >>> print(b)
Georg Brandl62eaaf62009-12-19 17:51:41 +0000670 <__main__.A object at 0x16D07CC>
Serhiy Storchakadba90392016-05-10 12:01:23 +0300671 >>> print(a)
Georg Brandl62eaaf62009-12-19 17:51:41 +0000672 <__main__.A object at 0x16D07CC>
Georg Brandld7413152009-10-11 21:25:26 +0000673
674Arguably the class has a name: even though it is bound to two names and invoked
675through the name B the created instance is still reported as an instance of
676class A. However, it is impossible to say whether the instance's name is a or
677b, since both names are bound to the same value.
678
679Generally speaking it should not be necessary for your code to "know the names"
680of particular values. Unless you are deliberately writing introspective
681programs, this is usually an indication that a change of approach might be
682beneficial.
683
684In comp.lang.python, Fredrik Lundh once gave an excellent analogy in answer to
685this question:
686
687 The same way as you get the name of that cat you found on your porch: the cat
688 (object) itself cannot tell you its name, and it doesn't really care -- so
689 the only way to find out what it's called is to ask all your neighbours
690 (namespaces) if it's their cat (object)...
691
692 ....and don't be surprised if you'll find that it's known by many names, or
693 no name at all!
694
695
696What's up with the comma operator's precedence?
697-----------------------------------------------
698
699Comma is not an operator in Python. Consider this session::
700
701 >>> "a" in "b", "a"
Georg Brandl62eaaf62009-12-19 17:51:41 +0000702 (False, 'a')
Georg Brandld7413152009-10-11 21:25:26 +0000703
704Since the comma is not an operator, but a separator between expressions the
705above is evaluated as if you had entered::
706
R David Murrayfdf95032013-06-19 16:58:26 -0400707 ("a" in "b"), "a"
Georg Brandld7413152009-10-11 21:25:26 +0000708
709not::
710
R David Murrayfdf95032013-06-19 16:58:26 -0400711 "a" in ("b", "a")
Georg Brandld7413152009-10-11 21:25:26 +0000712
713The same is true of the various assignment operators (``=``, ``+=`` etc). They
714are not truly operators but syntactic delimiters in assignment statements.
715
716
717Is there an equivalent of C's "?:" ternary operator?
718----------------------------------------------------
719
Antoine Pitrouc5b266e2011-12-03 22:11:11 +0100720Yes, there is. The syntax is as follows::
Georg Brandld7413152009-10-11 21:25:26 +0000721
722 [on_true] if [expression] else [on_false]
723
724 x, y = 50, 25
Georg Brandld7413152009-10-11 21:25:26 +0000725 small = x if x < y else y
726
Antoine Pitrouc5b266e2011-12-03 22:11:11 +0100727Before this syntax was introduced in Python 2.5, a common idiom was to use
728logical operators::
Georg Brandld7413152009-10-11 21:25:26 +0000729
Antoine Pitrouc5b266e2011-12-03 22:11:11 +0100730 [expression] and [on_true] or [on_false]
Georg Brandld7413152009-10-11 21:25:26 +0000731
Antoine Pitrouc5b266e2011-12-03 22:11:11 +0100732However, this idiom is unsafe, as it can give wrong results when *on_true*
733has a false boolean value. Therefore, it is always better to use
734the ``... if ... else ...`` form.
Georg Brandld7413152009-10-11 21:25:26 +0000735
736
737Is it possible to write obfuscated one-liners in Python?
738--------------------------------------------------------
739
740Yes. Usually this is done by nesting :keyword:`lambda` within
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200741:keyword:`!lambda`. See the following three examples, due to Ulf Bartelt::
Georg Brandld7413152009-10-11 21:25:26 +0000742
Georg Brandl62eaaf62009-12-19 17:51:41 +0000743 from functools import reduce
744
Georg Brandld7413152009-10-11 21:25:26 +0000745 # Primes < 1000
Georg Brandl62eaaf62009-12-19 17:51:41 +0000746 print(list(filter(None,map(lambda y:y*reduce(lambda x,y:x*y!=0,
747 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 +0000748
749 # First 10 Fibonacci numbers
Georg Brandl62eaaf62009-12-19 17:51:41 +0000750 print(list(map(lambda x,f=lambda x,f:(f(x-1,f)+f(x-2,f)) if x>1 else 1:
751 f(x,f), range(10))))
Georg Brandld7413152009-10-11 21:25:26 +0000752
753 # Mandelbrot set
Georg Brandl62eaaf62009-12-19 17:51:41 +0000754 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 +0000755 Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,Sy=Sy,L=lambda yc,Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,i=IM,
756 Sx=Sx,Sy=Sy:reduce(lambda x,y:x+y,map(lambda x,xc=Ru,yc=yc,Ru=Ru,Ro=Ro,
757 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
758 >=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(
759 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 +0000760 ))))(-2.1, 0.7, -1.2, 1.2, 30, 80, 24))
Georg Brandld7413152009-10-11 21:25:26 +0000761 # \___ ___/ \___ ___/ | | |__ lines on screen
762 # V V | |______ columns on screen
763 # | | |__________ maximum of "iterations"
764 # | |_________________ range on y axis
765 # |____________________________ range on x axis
766
767Don't try this at home, kids!
768
769
Lysandros Nikolaou1aeeaeb2019-03-10 12:30:11 +0100770.. _faq-positional-only-arguments:
771
772What does the slash(/) in the parameter list of a function mean?
773----------------------------------------------------------------
774
775A slash in the argument list of a function denotes that the parameters prior to
776it are positional-only. Positional-only parameters are the ones without an
777externally-usable name. Upon calling a function that accepts positional-only
778parameters, arguments are mapped to parameters based solely on their position.
779For example, :func:`pow` is a function that accepts positional-only parameters.
780Its documentation looks like this::
781
782 >>> help(pow)
783 Help on built-in function pow in module builtins:
784
785 pow(x, y, z=None, /)
786 Equivalent to x**y (with two arguments) or x**y % z (with three arguments)
787
788 Some types, such as ints, are able to use a more efficient algorithm when
789 invoked using the three argument form.
790
791The slash at the end of the parameter list means that all three parameters are
792positional-only. Thus, calling :func:`pow` with keyword aguments would lead to
793an error::
794
795 >>> pow(x=3, y=4)
796 Traceback (most recent call last):
797 File "<stdin>", line 1, in <module>
798 TypeError: pow() takes no keyword arguments
799
800Note that as of this writing this is only documentational and no valid syntax
801in Python, although there is :pep:`570`, which proposes a syntax for
802position-only parameters in Python.
803
804
Georg Brandld7413152009-10-11 21:25:26 +0000805Numbers and strings
806===================
807
808How do I specify hexadecimal and octal integers?
809------------------------------------------------
810
Georg Brandl62eaaf62009-12-19 17:51:41 +0000811To specify an octal digit, precede the octal value with a zero, and then a lower
812or uppercase "o". For example, to set the variable "a" to the octal value "10"
813(8 in decimal), type::
Georg Brandld7413152009-10-11 21:25:26 +0000814
Georg Brandl62eaaf62009-12-19 17:51:41 +0000815 >>> a = 0o10
Georg Brandld7413152009-10-11 21:25:26 +0000816 >>> a
817 8
818
819Hexadecimal is just as easy. Simply precede the hexadecimal number with a zero,
820and then a lower or uppercase "x". Hexadecimal digits can be specified in lower
821or uppercase. For example, in the Python interpreter::
822
823 >>> a = 0xa5
824 >>> a
825 165
826 >>> b = 0XB2
827 >>> b
828 178
829
830
Georg Brandl62eaaf62009-12-19 17:51:41 +0000831Why does -22 // 10 return -3?
832-----------------------------
Georg Brandld7413152009-10-11 21:25:26 +0000833
834It's primarily driven by the desire that ``i % j`` have the same sign as ``j``.
835If you want that, and also want::
836
Georg Brandl62eaaf62009-12-19 17:51:41 +0000837 i == (i // j) * j + (i % j)
Georg Brandld7413152009-10-11 21:25:26 +0000838
839then integer division has to return the floor. C also requires that identity to
Georg Brandl62eaaf62009-12-19 17:51:41 +0000840hold, and then compilers that truncate ``i // j`` need to make ``i % j`` have
841the same sign as ``i``.
Georg Brandld7413152009-10-11 21:25:26 +0000842
843There are few real use cases for ``i % j`` when ``j`` is negative. When ``j``
844is positive, there are many, and in virtually all of them it's more useful for
845``i % j`` to be ``>= 0``. If the clock says 10 now, what did it say 200 hours
846ago? ``-190 % 12 == 2`` is useful; ``-190 % 12 == -10`` is a bug waiting to
847bite.
848
849
850How do I convert a string to a number?
851--------------------------------------
852
853For integers, use the built-in :func:`int` type constructor, e.g. ``int('144')
854== 144``. Similarly, :func:`float` converts to floating-point,
855e.g. ``float('144') == 144.0``.
856
857By default, these interpret the number as decimal, so that ``int('0144') ==
858144`` and ``int('0x144')`` raises :exc:`ValueError`. ``int(string, base)`` takes
859the base to convert from as a second optional argument, so ``int('0x144', 16) ==
860324``. If the base is specified as 0, the number is interpreted using Python's
Eric V. Smithfc9a4d82014-04-14 07:41:52 -0400861rules: a leading '0o' indicates octal, and '0x' indicates a hex number.
Georg Brandld7413152009-10-11 21:25:26 +0000862
863Do not use the built-in function :func:`eval` if all you need is to convert
864strings to numbers. :func:`eval` will be significantly slower and it presents a
865security risk: someone could pass you a Python expression that might have
866unwanted side effects. For example, someone could pass
867``__import__('os').system("rm -rf $HOME")`` which would erase your home
868directory.
869
870:func:`eval` also has the effect of interpreting numbers as Python expressions,
Georg Brandl62eaaf62009-12-19 17:51:41 +0000871so that e.g. ``eval('09')`` gives a syntax error because Python does not allow
872leading '0' in a decimal number (except '0').
Georg Brandld7413152009-10-11 21:25:26 +0000873
874
875How do I convert a number to a string?
876--------------------------------------
877
878To convert, e.g., the number 144 to the string '144', use the built-in type
879constructor :func:`str`. If you want a hexadecimal or octal representation, use
Georg Brandl62eaaf62009-12-19 17:51:41 +0000880the built-in functions :func:`hex` or :func:`oct`. For fancy formatting, see
Martin Panterbc1ee462016-02-13 00:41:37 +0000881the :ref:`f-strings` and :ref:`formatstrings` sections,
882e.g. ``"{:04d}".format(144)`` yields
Eric V. Smith04d8a242014-04-14 07:52:53 -0400883``'0144'`` and ``"{:.3f}".format(1.0/3.0)`` yields ``'0.333'``.
Georg Brandld7413152009-10-11 21:25:26 +0000884
885
886How do I modify a string in place?
887----------------------------------
888
Antoine Pitrouc5b266e2011-12-03 22:11:11 +0100889You can't, because strings are immutable. In most situations, you should
890simply construct a new string from the various parts you want to assemble
891it from. However, if you need an object with the ability to modify in-place
Martin Panter7462b6492015-11-02 03:37:02 +0000892unicode data, try using an :class:`io.StringIO` object or the :mod:`array`
Antoine Pitrouc5b266e2011-12-03 22:11:11 +0100893module::
Georg Brandld7413152009-10-11 21:25:26 +0000894
R David Murrayfdf95032013-06-19 16:58:26 -0400895 >>> import io
Georg Brandld7413152009-10-11 21:25:26 +0000896 >>> s = "Hello, world"
Antoine Pitrouc5b266e2011-12-03 22:11:11 +0100897 >>> sio = io.StringIO(s)
898 >>> sio.getvalue()
899 'Hello, world'
900 >>> sio.seek(7)
901 7
902 >>> sio.write("there!")
903 6
904 >>> sio.getvalue()
Georg Brandld7413152009-10-11 21:25:26 +0000905 'Hello, there!'
906
907 >>> import array
Georg Brandl62eaaf62009-12-19 17:51:41 +0000908 >>> a = array.array('u', s)
909 >>> print(a)
910 array('u', 'Hello, world')
911 >>> a[0] = 'y'
912 >>> print(a)
R David Murrayfdf95032013-06-19 16:58:26 -0400913 array('u', 'yello, world')
Georg Brandl62eaaf62009-12-19 17:51:41 +0000914 >>> a.tounicode()
Georg Brandld7413152009-10-11 21:25:26 +0000915 'yello, world'
916
917
918How do I use strings to call functions/methods?
919-----------------------------------------------
920
921There are various techniques.
922
923* The best is to use a dictionary that maps strings to functions. The primary
924 advantage of this technique is that the strings do not need to match the names
925 of the functions. This is also the primary technique used to emulate a case
926 construct::
927
928 def a():
929 pass
930
931 def b():
932 pass
933
934 dispatch = {'go': a, 'stop': b} # Note lack of parens for funcs
935
936 dispatch[get_input()]() # Note trailing parens to call function
937
938* Use the built-in function :func:`getattr`::
939
940 import foo
941 getattr(foo, 'bar')()
942
943 Note that :func:`getattr` works on any object, including classes, class
944 instances, modules, and so on.
945
946 This is used in several places in the standard library, like this::
947
948 class Foo:
949 def do_foo(self):
950 ...
951
952 def do_bar(self):
953 ...
954
955 f = getattr(foo_instance, 'do_' + opname)
956 f()
957
958
959* Use :func:`locals` or :func:`eval` to resolve the function name::
960
961 def myFunc():
Georg Brandl62eaaf62009-12-19 17:51:41 +0000962 print("hello")
Georg Brandld7413152009-10-11 21:25:26 +0000963
964 fname = "myFunc"
965
966 f = locals()[fname]
967 f()
968
969 f = eval(fname)
970 f()
971
972 Note: Using :func:`eval` is slow and dangerous. If you don't have absolute
973 control over the contents of the string, someone could pass a string that
974 resulted in an arbitrary function being executed.
975
976Is there an equivalent to Perl's chomp() for removing trailing newlines from strings?
977-------------------------------------------------------------------------------------
978
Antoine Pitrouf3520402011-12-03 22:19:55 +0100979You can use ``S.rstrip("\r\n")`` to remove all occurrences of any line
980terminator from the end of the string ``S`` without removing other trailing
981whitespace. If the string ``S`` represents more than one line, with several
982empty lines at the end, the line terminators for all the blank lines will
983be removed::
Georg Brandld7413152009-10-11 21:25:26 +0000984
985 >>> lines = ("line 1 \r\n"
986 ... "\r\n"
987 ... "\r\n")
988 >>> lines.rstrip("\n\r")
Georg Brandl62eaaf62009-12-19 17:51:41 +0000989 'line 1 '
Georg Brandld7413152009-10-11 21:25:26 +0000990
991Since this is typically only desired when reading text one line at a time, using
992``S.rstrip()`` this way works well.
993
Georg Brandld7413152009-10-11 21:25:26 +0000994
995Is there a scanf() or sscanf() equivalent?
996------------------------------------------
997
998Not as such.
999
1000For simple input parsing, the easiest approach is usually to split the line into
1001whitespace-delimited words using the :meth:`~str.split` method of string objects
1002and then convert decimal strings to numeric values using :func:`int` or
1003:func:`float`. ``split()`` supports an optional "sep" parameter which is useful
1004if the line uses something other than whitespace as a separator.
1005
Brian Curtin5a7a52f2010-09-23 13:45:21 +00001006For more complicated input parsing, regular expressions are more powerful
Georg Brandl60203b42010-10-06 10:11:56 +00001007than C's :c:func:`sscanf` and better suited for the task.
Georg Brandld7413152009-10-11 21:25:26 +00001008
1009
Georg Brandl62eaaf62009-12-19 17:51:41 +00001010What does 'UnicodeDecodeError' or 'UnicodeEncodeError' error mean?
1011-------------------------------------------------------------------
Georg Brandld7413152009-10-11 21:25:26 +00001012
Georg Brandl62eaaf62009-12-19 17:51:41 +00001013See the :ref:`unicode-howto`.
Georg Brandld7413152009-10-11 21:25:26 +00001014
1015
Antoine Pitrou432259f2011-12-09 23:10:31 +01001016Performance
1017===========
1018
1019My program is too slow. How do I speed it up?
1020---------------------------------------------
1021
1022That's a tough one, in general. First, here are a list of things to
1023remember before diving further:
1024
Georg Brandl300a6912012-03-14 22:40:08 +01001025* Performance characteristics vary across Python implementations. This FAQ
Antoine Pitrou432259f2011-12-09 23:10:31 +01001026 focusses on :term:`CPython`.
Georg Brandl300a6912012-03-14 22:40:08 +01001027* Behaviour can vary across operating systems, especially when talking about
Antoine Pitrou432259f2011-12-09 23:10:31 +01001028 I/O or multi-threading.
1029* You should always find the hot spots in your program *before* attempting to
1030 optimize any code (see the :mod:`profile` module).
1031* Writing benchmark scripts will allow you to iterate quickly when searching
1032 for improvements (see the :mod:`timeit` module).
1033* It is highly recommended to have good code coverage (through unit testing
1034 or any other technique) before potentially introducing regressions hidden
1035 in sophisticated optimizations.
1036
1037That being said, there are many tricks to speed up Python code. Here are
1038some general principles which go a long way towards reaching acceptable
1039performance levels:
1040
1041* Making your algorithms faster (or changing to faster ones) can yield
1042 much larger benefits than trying to sprinkle micro-optimization tricks
1043 all over your code.
1044
1045* Use the right data structures. Study documentation for the :ref:`bltin-types`
1046 and the :mod:`collections` module.
1047
1048* When the standard library provides a primitive for doing something, it is
1049 likely (although not guaranteed) to be faster than any alternative you
1050 may come up with. This is doubly true for primitives written in C, such
1051 as builtins and some extension types. For example, be sure to use
1052 either the :meth:`list.sort` built-in method or the related :func:`sorted`
Senthil Kumarand03d1d42016-01-01 23:25:58 -08001053 function to do sorting (and see the :ref:`sortinghowto` for examples
Antoine Pitrou432259f2011-12-09 23:10:31 +01001054 of moderately advanced usage).
1055
1056* Abstractions tend to create indirections and force the interpreter to work
1057 more. If the levels of indirection outweigh the amount of useful work
1058 done, your program will be slower. You should avoid excessive abstraction,
1059 especially under the form of tiny functions or methods (which are also often
1060 detrimental to readability).
1061
1062If you have reached the limit of what pure Python can allow, there are tools
1063to take you further away. For example, `Cython <http://cython.org>`_ can
1064compile a slightly modified version of Python code into a C extension, and
1065can be used on many different platforms. Cython can take advantage of
1066compilation (and optional type annotations) to make your code significantly
1067faster than when interpreted. If you are confident in your C programming
1068skills, you can also :ref:`write a C extension module <extending-index>`
1069yourself.
1070
1071.. seealso::
1072 The wiki page devoted to `performance tips
Georg Brandle73778c2014-10-29 08:36:35 +01001073 <https://wiki.python.org/moin/PythonSpeed/PerformanceTips>`_.
Antoine Pitrou432259f2011-12-09 23:10:31 +01001074
1075.. _efficient_string_concatenation:
1076
Antoine Pitroufd9ebd42011-11-25 16:33:53 +01001077What is the most efficient way to concatenate many strings together?
1078--------------------------------------------------------------------
1079
1080:class:`str` and :class:`bytes` objects are immutable, therefore concatenating
1081many strings together is inefficient as each concatenation creates a new
1082object. In the general case, the total runtime cost is quadratic in the
1083total string length.
1084
1085To accumulate many :class:`str` objects, the recommended idiom is to place
1086them into a list and call :meth:`str.join` at the end::
1087
1088 chunks = []
1089 for s in my_strings:
1090 chunks.append(s)
1091 result = ''.join(chunks)
1092
1093(another reasonably efficient idiom is to use :class:`io.StringIO`)
1094
1095To accumulate many :class:`bytes` objects, the recommended idiom is to extend
1096a :class:`bytearray` object using in-place concatenation (the ``+=`` operator)::
1097
1098 result = bytearray()
1099 for b in my_bytes_objects:
1100 result += b
1101
1102
Georg Brandld7413152009-10-11 21:25:26 +00001103Sequences (Tuples/Lists)
1104========================
1105
1106How do I convert between tuples and lists?
1107------------------------------------------
1108
1109The type constructor ``tuple(seq)`` converts any sequence (actually, any
1110iterable) into a tuple with the same items in the same order.
1111
1112For example, ``tuple([1, 2, 3])`` yields ``(1, 2, 3)`` and ``tuple('abc')``
1113yields ``('a', 'b', 'c')``. If the argument is a tuple, it does not make a copy
1114but returns the same object, so it is cheap to call :func:`tuple` when you
1115aren't sure that an object is already a tuple.
1116
1117The type constructor ``list(seq)`` converts any sequence or iterable into a list
1118with the same items in the same order. For example, ``list((1, 2, 3))`` yields
1119``[1, 2, 3]`` and ``list('abc')`` yields ``['a', 'b', 'c']``. If the argument
1120is a list, it makes a copy just like ``seq[:]`` would.
1121
1122
1123What's a negative index?
1124------------------------
1125
1126Python sequences are indexed with positive numbers and negative numbers. For
1127positive numbers 0 is the first index 1 is the second index and so forth. For
1128negative indices -1 is the last index and -2 is the penultimate (next to last)
1129index and so forth. Think of ``seq[-n]`` as the same as ``seq[len(seq)-n]``.
1130
1131Using negative indices can be very convenient. For example ``S[:-1]`` is all of
1132the string except for its last character, which is useful for removing the
1133trailing newline from a string.
1134
1135
1136How do I iterate over a sequence in reverse order?
1137--------------------------------------------------
1138
Georg Brandlc4a55fc2010-02-06 18:46:57 +00001139Use the :func:`reversed` built-in function, which is new in Python 2.4::
Georg Brandld7413152009-10-11 21:25:26 +00001140
1141 for x in reversed(sequence):
Serhiy Storchakadba90392016-05-10 12:01:23 +03001142 ... # do something with x ...
Georg Brandld7413152009-10-11 21:25:26 +00001143
1144This won't touch your original sequence, but build a new copy with reversed
1145order to iterate over.
1146
1147With Python 2.3, you can use an extended slice syntax::
1148
1149 for x in sequence[::-1]:
Serhiy Storchakadba90392016-05-10 12:01:23 +03001150 ... # do something with x ...
Georg Brandld7413152009-10-11 21:25:26 +00001151
1152
1153How do you remove duplicates from a list?
1154-----------------------------------------
1155
1156See the Python Cookbook for a long discussion of many ways to do this:
1157
Serhiy Storchaka6dff0202016-05-07 10:49:07 +03001158 https://code.activestate.com/recipes/52560/
Georg Brandld7413152009-10-11 21:25:26 +00001159
1160If you don't mind reordering the list, sort it and then scan from the end of the
1161list, deleting duplicates as you go::
1162
Georg Brandl62eaaf62009-12-19 17:51:41 +00001163 if mylist:
1164 mylist.sort()
1165 last = mylist[-1]
1166 for i in range(len(mylist)-2, -1, -1):
1167 if last == mylist[i]:
1168 del mylist[i]
Georg Brandld7413152009-10-11 21:25:26 +00001169 else:
Georg Brandl62eaaf62009-12-19 17:51:41 +00001170 last = mylist[i]
Georg Brandld7413152009-10-11 21:25:26 +00001171
Antoine Pitrouf3520402011-12-03 22:19:55 +01001172If all elements of the list may be used as set keys (i.e. they are all
1173:term:`hashable`) this is often faster ::
Georg Brandld7413152009-10-11 21:25:26 +00001174
Georg Brandl62eaaf62009-12-19 17:51:41 +00001175 mylist = list(set(mylist))
Georg Brandld7413152009-10-11 21:25:26 +00001176
1177This converts the list into a set, thereby removing duplicates, and then back
1178into a list.
1179
1180
1181How do you make an array in Python?
1182-----------------------------------
1183
1184Use a list::
1185
1186 ["this", 1, "is", "an", "array"]
1187
1188Lists are equivalent to C or Pascal arrays in their time complexity; the primary
1189difference is that a Python list can contain objects of many different types.
1190
1191The ``array`` module also provides methods for creating arrays of fixed types
1192with compact representations, but they are slower to index than lists. Also
1193note that the Numeric extensions and others define array-like structures with
1194various characteristics as well.
1195
1196To get Lisp-style linked lists, you can emulate cons cells using tuples::
1197
1198 lisp_list = ("like", ("this", ("example", None) ) )
1199
1200If mutability is desired, you could use lists instead of tuples. Here the
1201analogue of lisp car is ``lisp_list[0]`` and the analogue of cdr is
1202``lisp_list[1]``. Only do this if you're sure you really need to, because it's
1203usually a lot slower than using Python lists.
1204
1205
Martin Panter7f02d6d2015-09-07 02:08:55 +00001206.. _faq-multidimensional-list:
1207
Georg Brandld7413152009-10-11 21:25:26 +00001208How do I create a multidimensional list?
1209----------------------------------------
1210
1211You probably tried to make a multidimensional array like this::
1212
R David Murrayfdf95032013-06-19 16:58:26 -04001213 >>> A = [[None] * 2] * 3
Georg Brandld7413152009-10-11 21:25:26 +00001214
Senthil Kumaran77493202016-06-04 20:07:34 -07001215This looks correct if you print it:
1216
1217.. testsetup::
1218
1219 A = [[None] * 2] * 3
1220
1221.. doctest::
Georg Brandld7413152009-10-11 21:25:26 +00001222
1223 >>> A
1224 [[None, None], [None, None], [None, None]]
1225
1226But when you assign a value, it shows up in multiple places:
1227
Senthil Kumaran77493202016-06-04 20:07:34 -07001228.. testsetup::
1229
1230 A = [[None] * 2] * 3
1231
1232.. doctest::
1233
1234 >>> A[0][0] = 5
1235 >>> A
1236 [[5, None], [5, None], [5, None]]
Georg Brandld7413152009-10-11 21:25:26 +00001237
1238The reason is that replicating a list with ``*`` doesn't create copies, it only
1239creates references to the existing objects. The ``*3`` creates a list
1240containing 3 references to the same list of length two. Changes to one row will
1241show in all rows, which is almost certainly not what you want.
1242
1243The suggested approach is to create a list of the desired length first and then
1244fill in each element with a newly created list::
1245
1246 A = [None] * 3
1247 for i in range(3):
1248 A[i] = [None] * 2
1249
1250This generates a list containing 3 different lists of length two. You can also
1251use a list comprehension::
1252
1253 w, h = 2, 3
1254 A = [[None] * w for i in range(h)]
1255
Benjamin Peterson6d3ad2f2016-05-26 22:51:32 -07001256Or, you can use an extension that provides a matrix datatype; `NumPy
Ezio Melottic1f58392013-06-09 01:04:21 +03001257<http://www.numpy.org/>`_ is the best known.
Georg Brandld7413152009-10-11 21:25:26 +00001258
1259
1260How do I apply a method to a sequence of objects?
1261-------------------------------------------------
1262
1263Use a list comprehension::
1264
Georg Brandl62eaaf62009-12-19 17:51:41 +00001265 result = [obj.method() for obj in mylist]
Georg Brandld7413152009-10-11 21:25:26 +00001266
Larry Hastings3732ed22014-03-15 21:13:56 -07001267.. _faq-augmented-assignment-tuple-error:
Georg Brandld7413152009-10-11 21:25:26 +00001268
R David Murraybcf06d32013-05-20 10:32:46 -04001269Why does a_tuple[i] += ['item'] raise an exception when the addition works?
1270---------------------------------------------------------------------------
1271
1272This is because of a combination of the fact that augmented assignment
1273operators are *assignment* operators, and the difference between mutable and
1274immutable objects in Python.
1275
1276This discussion applies in general when augmented assignment operators are
1277applied to elements of a tuple that point to mutable objects, but we'll use
1278a ``list`` and ``+=`` as our exemplar.
1279
1280If you wrote::
1281
1282 >>> a_tuple = (1, 2)
1283 >>> a_tuple[0] += 1
1284 Traceback (most recent call last):
1285 ...
1286 TypeError: 'tuple' object does not support item assignment
1287
1288The reason for the exception should be immediately clear: ``1`` is added to the
1289object ``a_tuple[0]`` points to (``1``), producing the result object, ``2``,
1290but when we attempt to assign the result of the computation, ``2``, to element
1291``0`` of the tuple, we get an error because we can't change what an element of
1292a tuple points to.
1293
1294Under the covers, what this augmented assignment statement is doing is
1295approximately this::
1296
R David Murray95ae9922013-05-21 11:44:41 -04001297 >>> result = a_tuple[0] + 1
R David Murraybcf06d32013-05-20 10:32:46 -04001298 >>> a_tuple[0] = result
1299 Traceback (most recent call last):
1300 ...
1301 TypeError: 'tuple' object does not support item assignment
1302
1303It is the assignment part of the operation that produces the error, since a
1304tuple is immutable.
1305
1306When you write something like::
1307
1308 >>> a_tuple = (['foo'], 'bar')
1309 >>> a_tuple[0] += ['item']
1310 Traceback (most recent call last):
1311 ...
1312 TypeError: 'tuple' object does not support item assignment
1313
1314The exception is a bit more surprising, and even more surprising is the fact
1315that even though there was an error, the append worked::
1316
1317 >>> a_tuple[0]
1318 ['foo', 'item']
1319
R David Murray95ae9922013-05-21 11:44:41 -04001320To see why this happens, you need to know that (a) if an object implements an
1321``__iadd__`` magic method, it gets called when the ``+=`` augmented assignment
1322is executed, and its return value is what gets used in the assignment statement;
1323and (b) for lists, ``__iadd__`` is equivalent to calling ``extend`` on the list
1324and returning the list. That's why we say that for lists, ``+=`` is a
1325"shorthand" for ``list.extend``::
R David Murraybcf06d32013-05-20 10:32:46 -04001326
1327 >>> a_list = []
1328 >>> a_list += [1]
1329 >>> a_list
1330 [1]
1331
R David Murray95ae9922013-05-21 11:44:41 -04001332This is equivalent to::
R David Murraybcf06d32013-05-20 10:32:46 -04001333
1334 >>> result = a_list.__iadd__([1])
1335 >>> a_list = result
1336
1337The object pointed to by a_list has been mutated, and the pointer to the
1338mutated object is assigned back to ``a_list``. The end result of the
1339assignment is a no-op, since it is a pointer to the same object that ``a_list``
1340was previously pointing to, but the assignment still happens.
1341
1342Thus, in our tuple example what is happening is equivalent to::
1343
1344 >>> result = a_tuple[0].__iadd__(['item'])
1345 >>> a_tuple[0] = result
1346 Traceback (most recent call last):
1347 ...
1348 TypeError: 'tuple' object does not support item assignment
1349
1350The ``__iadd__`` succeeds, and thus the list is extended, but even though
1351``result`` points to the same object that ``a_tuple[0]`` already points to,
1352that final assignment still results in an error, because tuples are immutable.
1353
1354
Georg Brandld7413152009-10-11 21:25:26 +00001355I want to do a complicated sort: can you do a Schwartzian Transform in Python?
1356------------------------------------------------------------------------------
1357
1358The technique, attributed to Randal Schwartz of the Perl community, sorts the
1359elements of a list by a metric which maps each element to its "sort value". In
Berker Peksag5b6a14d2016-06-01 13:54:33 -07001360Python, use the ``key`` argument for the :meth:`list.sort` method::
Georg Brandld7413152009-10-11 21:25:26 +00001361
1362 Isorted = L[:]
1363 Isorted.sort(key=lambda s: int(s[10:15]))
1364
Georg Brandld7413152009-10-11 21:25:26 +00001365
1366How can I sort one list by values from another list?
1367----------------------------------------------------
1368
Georg Brandl62eaaf62009-12-19 17:51:41 +00001369Merge them into an iterator of tuples, sort the resulting list, and then pick
Georg Brandld7413152009-10-11 21:25:26 +00001370out the element you want. ::
1371
1372 >>> list1 = ["what", "I'm", "sorting", "by"]
1373 >>> list2 = ["something", "else", "to", "sort"]
1374 >>> pairs = zip(list1, list2)
Georg Brandl62eaaf62009-12-19 17:51:41 +00001375 >>> pairs = sorted(pairs)
Georg Brandld7413152009-10-11 21:25:26 +00001376 >>> pairs
Georg Brandl62eaaf62009-12-19 17:51:41 +00001377 [("I'm", 'else'), ('by', 'sort'), ('sorting', 'to'), ('what', 'something')]
1378 >>> result = [x[1] for x in pairs]
Georg Brandld7413152009-10-11 21:25:26 +00001379 >>> result
1380 ['else', 'sort', 'to', 'something']
1381
Georg Brandl62eaaf62009-12-19 17:51:41 +00001382
Georg Brandld7413152009-10-11 21:25:26 +00001383An alternative for the last step is::
1384
Georg Brandl62eaaf62009-12-19 17:51:41 +00001385 >>> result = []
1386 >>> for p in pairs: result.append(p[1])
Georg Brandld7413152009-10-11 21:25:26 +00001387
1388If you find this more legible, you might prefer to use this instead of the final
1389list comprehension. However, it is almost twice as slow for long lists. Why?
1390First, the ``append()`` operation has to reallocate memory, and while it uses
1391some tricks to avoid doing that each time, it still has to do it occasionally,
1392and that costs quite a bit. Second, the expression "result.append" requires an
1393extra attribute lookup, and third, there's a speed reduction from having to make
1394all those function calls.
1395
1396
1397Objects
1398=======
1399
1400What is a class?
1401----------------
1402
1403A class is the particular object type created by executing a class statement.
1404Class objects are used as templates to create instance objects, which embody
1405both the data (attributes) and code (methods) specific to a datatype.
1406
1407A class can be based on one or more other classes, called its base class(es). It
1408then inherits the attributes and methods of its base classes. This allows an
1409object model to be successively refined by inheritance. You might have a
1410generic ``Mailbox`` class that provides basic accessor methods for a mailbox,
1411and subclasses such as ``MboxMailbox``, ``MaildirMailbox``, ``OutlookMailbox``
1412that handle various specific mailbox formats.
1413
1414
1415What is a method?
1416-----------------
1417
1418A method is a function on some object ``x`` that you normally call as
1419``x.name(arguments...)``. Methods are defined as functions inside the class
1420definition::
1421
1422 class C:
Serhiy Storchakadba90392016-05-10 12:01:23 +03001423 def meth(self, arg):
Georg Brandld7413152009-10-11 21:25:26 +00001424 return arg * 2 + self.attribute
1425
1426
1427What is self?
1428-------------
1429
1430Self is merely a conventional name for the first argument of a method. A method
1431defined as ``meth(self, a, b, c)`` should be called as ``x.meth(a, b, c)`` for
1432some instance ``x`` of the class in which the definition occurs; the called
1433method will think it is called as ``meth(x, a, b, c)``.
1434
1435See also :ref:`why-self`.
1436
1437
1438How do I check if an object is an instance of a given class or of a subclass of it?
1439-----------------------------------------------------------------------------------
1440
1441Use the built-in function ``isinstance(obj, cls)``. You can check if an object
1442is an instance of any of a number of classes by providing a tuple instead of a
1443single class, e.g. ``isinstance(obj, (class1, class2, ...))``, and can also
1444check whether an object is one of Python's built-in types, e.g.
Georg Brandl62eaaf62009-12-19 17:51:41 +00001445``isinstance(obj, str)`` or ``isinstance(obj, (int, float, complex))``.
Georg Brandld7413152009-10-11 21:25:26 +00001446
1447Note that most programs do not use :func:`isinstance` on user-defined classes
1448very often. If you are developing the classes yourself, a more proper
1449object-oriented style is to define methods on the classes that encapsulate a
1450particular behaviour, instead of checking the object's class and doing a
1451different thing based on what class it is. For example, if you have a function
1452that does something::
1453
Georg Brandl62eaaf62009-12-19 17:51:41 +00001454 def search(obj):
Georg Brandld7413152009-10-11 21:25:26 +00001455 if isinstance(obj, Mailbox):
Serhiy Storchakadba90392016-05-10 12:01:23 +03001456 ... # code to search a mailbox
Georg Brandld7413152009-10-11 21:25:26 +00001457 elif isinstance(obj, Document):
Serhiy Storchakadba90392016-05-10 12:01:23 +03001458 ... # code to search a document
Georg Brandld7413152009-10-11 21:25:26 +00001459 elif ...
1460
1461A better approach is to define a ``search()`` method on all the classes and just
1462call it::
1463
1464 class Mailbox:
1465 def search(self):
Serhiy Storchakadba90392016-05-10 12:01:23 +03001466 ... # code to search a mailbox
Georg Brandld7413152009-10-11 21:25:26 +00001467
1468 class Document:
1469 def search(self):
Serhiy Storchakadba90392016-05-10 12:01:23 +03001470 ... # code to search a document
Georg Brandld7413152009-10-11 21:25:26 +00001471
1472 obj.search()
1473
1474
1475What is delegation?
1476-------------------
1477
1478Delegation is an object oriented technique (also called a design pattern).
1479Let's say you have an object ``x`` and want to change the behaviour of just one
1480of its methods. You can create a new class that provides a new implementation
1481of the method you're interested in changing and delegates all other methods to
1482the corresponding method of ``x``.
1483
1484Python programmers can easily implement delegation. For example, the following
1485class implements a class that behaves like a file but converts all written data
1486to uppercase::
1487
1488 class UpperOut:
1489
1490 def __init__(self, outfile):
1491 self._outfile = outfile
1492
1493 def write(self, s):
1494 self._outfile.write(s.upper())
1495
1496 def __getattr__(self, name):
1497 return getattr(self._outfile, name)
1498
1499Here the ``UpperOut`` class redefines the ``write()`` method to convert the
1500argument string to uppercase before calling the underlying
1501``self.__outfile.write()`` method. All other methods are delegated to the
1502underlying ``self.__outfile`` object. The delegation is accomplished via the
1503``__getattr__`` method; consult :ref:`the language reference <attribute-access>`
1504for more information about controlling attribute access.
1505
1506Note that for more general cases delegation can get trickier. When attributes
1507must be set as well as retrieved, the class must define a :meth:`__setattr__`
1508method too, and it must do so carefully. The basic implementation of
1509:meth:`__setattr__` is roughly equivalent to the following::
1510
1511 class X:
1512 ...
1513 def __setattr__(self, name, value):
1514 self.__dict__[name] = value
1515 ...
1516
1517Most :meth:`__setattr__` implementations must modify ``self.__dict__`` to store
1518local state for self without causing an infinite recursion.
1519
1520
1521How do I call a method defined in a base class from a derived class that overrides it?
1522--------------------------------------------------------------------------------------
1523
Georg Brandl62eaaf62009-12-19 17:51:41 +00001524Use the built-in :func:`super` function::
Georg Brandld7413152009-10-11 21:25:26 +00001525
1526 class Derived(Base):
Serhiy Storchakadba90392016-05-10 12:01:23 +03001527 def meth(self):
Georg Brandld7413152009-10-11 21:25:26 +00001528 super(Derived, self).meth()
1529
Georg Brandl62eaaf62009-12-19 17:51:41 +00001530For version prior to 3.0, you may be using classic classes: For a class
1531definition such as ``class Derived(Base): ...`` you can call method ``meth()``
1532defined in ``Base`` (or one of ``Base``'s base classes) as ``Base.meth(self,
1533arguments...)``. Here, ``Base.meth`` is an unbound method, so you need to
1534provide the ``self`` argument.
Georg Brandld7413152009-10-11 21:25:26 +00001535
1536
1537How can I organize my code to make it easier to change the base class?
1538----------------------------------------------------------------------
1539
1540You could define an alias for the base class, assign the real base class to it
1541before your class definition, and use the alias throughout your class. Then all
1542you have to change is the value assigned to the alias. Incidentally, this trick
1543is also handy if you want to decide dynamically (e.g. depending on availability
1544of resources) which base class to use. Example::
1545
1546 BaseAlias = <real base class>
1547
1548 class Derived(BaseAlias):
1549 def meth(self):
1550 BaseAlias.meth(self)
1551 ...
1552
1553
1554How do I create static class data and static class methods?
1555-----------------------------------------------------------
1556
Georg Brandl62eaaf62009-12-19 17:51:41 +00001557Both static data and static methods (in the sense of C++ or Java) are supported
1558in Python.
Georg Brandld7413152009-10-11 21:25:26 +00001559
1560For static data, simply define a class attribute. To assign a new value to the
1561attribute, you have to explicitly use the class name in the assignment::
1562
1563 class C:
1564 count = 0 # number of times C.__init__ called
1565
1566 def __init__(self):
1567 C.count = C.count + 1
1568
1569 def getcount(self):
1570 return C.count # or return self.count
1571
1572``c.count`` also refers to ``C.count`` for any ``c`` such that ``isinstance(c,
1573C)`` holds, unless overridden by ``c`` itself or by some class on the base-class
1574search path from ``c.__class__`` back to ``C``.
1575
1576Caution: within a method of C, an assignment like ``self.count = 42`` creates a
Georg Brandl62eaaf62009-12-19 17:51:41 +00001577new and unrelated instance named "count" in ``self``'s own dict. Rebinding of a
1578class-static data name must always specify the class whether inside a method or
1579not::
Georg Brandld7413152009-10-11 21:25:26 +00001580
1581 C.count = 314
1582
Antoine Pitrouf3520402011-12-03 22:19:55 +01001583Static methods are possible::
Georg Brandld7413152009-10-11 21:25:26 +00001584
1585 class C:
1586 @staticmethod
1587 def static(arg1, arg2, arg3):
1588 # No 'self' parameter!
1589 ...
1590
1591However, a far more straightforward way to get the effect of a static method is
1592via a simple module-level function::
1593
1594 def getcount():
1595 return C.count
1596
1597If your code is structured so as to define one class (or tightly related class
1598hierarchy) per module, this supplies the desired encapsulation.
1599
1600
1601How can I overload constructors (or methods) in Python?
1602-------------------------------------------------------
1603
1604This answer actually applies to all methods, but the question usually comes up
1605first in the context of constructors.
1606
1607In C++ you'd write
1608
1609.. code-block:: c
1610
1611 class C {
1612 C() { cout << "No arguments\n"; }
1613 C(int i) { cout << "Argument is " << i << "\n"; }
1614 }
1615
1616In Python you have to write a single constructor that catches all cases using
1617default arguments. For example::
1618
1619 class C:
1620 def __init__(self, i=None):
1621 if i is None:
Georg Brandl62eaaf62009-12-19 17:51:41 +00001622 print("No arguments")
Georg Brandld7413152009-10-11 21:25:26 +00001623 else:
Georg Brandl62eaaf62009-12-19 17:51:41 +00001624 print("Argument is", i)
Georg Brandld7413152009-10-11 21:25:26 +00001625
1626This is not entirely equivalent, but close enough in practice.
1627
1628You could also try a variable-length argument list, e.g. ::
1629
1630 def __init__(self, *args):
1631 ...
1632
1633The same approach works for all method definitions.
1634
1635
1636I try to use __spam and I get an error about _SomeClassName__spam.
1637------------------------------------------------------------------
1638
1639Variable names with double leading underscores are "mangled" to provide a simple
1640but effective way to define class private variables. Any identifier of the form
1641``__spam`` (at least two leading underscores, at most one trailing underscore)
1642is textually replaced with ``_classname__spam``, where ``classname`` is the
1643current class name with any leading underscores stripped.
1644
1645This doesn't guarantee privacy: an outside user can still deliberately access
1646the "_classname__spam" attribute, and private values are visible in the object's
1647``__dict__``. Many Python programmers never bother to use private variable
1648names at all.
1649
1650
1651My class defines __del__ but it is not called when I delete the object.
1652-----------------------------------------------------------------------
1653
1654There are several possible reasons for this.
1655
1656The del statement does not necessarily call :meth:`__del__` -- it simply
1657decrements the object's reference count, and if this reaches zero
1658:meth:`__del__` is called.
1659
1660If your data structures contain circular links (e.g. a tree where each child has
1661a parent reference and each parent has a list of children) the reference counts
1662will never go back to zero. Once in a while Python runs an algorithm to detect
1663such cycles, but the garbage collector might run some time after the last
1664reference to your data structure vanishes, so your :meth:`__del__` method may be
1665called at an inconvenient and random time. This is inconvenient if you're trying
1666to reproduce a problem. Worse, the order in which object's :meth:`__del__`
1667methods are executed is arbitrary. You can run :func:`gc.collect` to force a
1668collection, but there *are* pathological cases where objects will never be
1669collected.
1670
1671Despite the cycle collector, it's still a good idea to define an explicit
1672``close()`` method on objects to be called whenever you're done with them. The
Gregory P. Smithe9d978f2017-08-28 13:43:26 -07001673``close()`` method can then remove attributes that refer to subobjects. Don't
Georg Brandld7413152009-10-11 21:25:26 +00001674call :meth:`__del__` directly -- :meth:`__del__` should call ``close()`` and
1675``close()`` should make sure that it can be called more than once for the same
1676object.
1677
1678Another way to avoid cyclical references is to use the :mod:`weakref` module,
1679which allows you to point to objects without incrementing their reference count.
1680Tree data structures, for instance, should use weak references for their parent
1681and sibling references (if they need them!).
1682
Georg Brandl62eaaf62009-12-19 17:51:41 +00001683.. XXX relevant for Python 3?
1684
1685 If the object has ever been a local variable in a function that caught an
1686 expression in an except clause, chances are that a reference to the object
1687 still exists in that function's stack frame as contained in the stack trace.
1688 Normally, calling :func:`sys.exc_clear` will take care of this by clearing
1689 the last recorded exception.
Georg Brandld7413152009-10-11 21:25:26 +00001690
1691Finally, if your :meth:`__del__` method raises an exception, a warning message
1692is printed to :data:`sys.stderr`.
1693
1694
1695How do I get a list of all instances of a given class?
1696------------------------------------------------------
1697
1698Python does not keep track of all instances of a class (or of a built-in type).
1699You can program the class's constructor to keep track of all instances by
1700keeping a list of weak references to each instance.
1701
1702
Georg Brandld8ede4f2013-10-12 18:14:25 +02001703Why does the result of ``id()`` appear to be not unique?
1704--------------------------------------------------------
1705
1706The :func:`id` builtin returns an integer that is guaranteed to be unique during
1707the lifetime of the object. Since in CPython, this is the object's memory
1708address, it happens frequently that after an object is deleted from memory, the
1709next freshly created object is allocated at the same position in memory. This
1710is illustrated by this example:
1711
Senthil Kumaran77493202016-06-04 20:07:34 -07001712>>> id(1000) # doctest: +SKIP
Georg Brandld8ede4f2013-10-12 18:14:25 +0200171313901272
Senthil Kumaran77493202016-06-04 20:07:34 -07001714>>> id(2000) # doctest: +SKIP
Georg Brandld8ede4f2013-10-12 18:14:25 +0200171513901272
1716
1717The two ids belong to different integer objects that are created before, and
1718deleted immediately after execution of the ``id()`` call. To be sure that
1719objects whose id you want to examine are still alive, create another reference
1720to the object:
1721
1722>>> a = 1000; b = 2000
Senthil Kumaran77493202016-06-04 20:07:34 -07001723>>> id(a) # doctest: +SKIP
Georg Brandld8ede4f2013-10-12 18:14:25 +0200172413901272
Senthil Kumaran77493202016-06-04 20:07:34 -07001725>>> id(b) # doctest: +SKIP
Georg Brandld8ede4f2013-10-12 18:14:25 +0200172613891296
1727
1728
Georg Brandld7413152009-10-11 21:25:26 +00001729Modules
1730=======
1731
1732How do I create a .pyc file?
1733----------------------------
1734
R David Murrayd913d9d2013-12-13 12:29:29 -05001735When a module is imported for the first time (or when the source file has
1736changed since the current compiled file was created) a ``.pyc`` file containing
1737the compiled code should be created in a ``__pycache__`` subdirectory of the
1738directory containing the ``.py`` file. The ``.pyc`` file will have a
1739filename that starts with the same name as the ``.py`` file, and ends with
1740``.pyc``, with a middle component that depends on the particular ``python``
1741binary that created it. (See :pep:`3147` for details.)
Georg Brandld7413152009-10-11 21:25:26 +00001742
R David Murrayd913d9d2013-12-13 12:29:29 -05001743One reason that a ``.pyc`` file may not be created is a permissions problem
1744with the directory containing the source file, meaning that the ``__pycache__``
1745subdirectory cannot be created. This can happen, for example, if you develop as
1746one user but run as another, such as if you are testing with a web server.
1747
1748Unless the :envvar:`PYTHONDONTWRITEBYTECODE` environment variable is set,
1749creation of a .pyc file is automatic if you're importing a module and Python
1750has the ability (permissions, free space, etc...) to create a ``__pycache__``
1751subdirectory and write the compiled module to that subdirectory.
Georg Brandld7413152009-10-11 21:25:26 +00001752
R David Murrayfdf95032013-06-19 16:58:26 -04001753Running Python on a top level script is not considered an import and no
1754``.pyc`` will be created. For example, if you have a top-level module
R David Murrayd913d9d2013-12-13 12:29:29 -05001755``foo.py`` that imports another module ``xyz.py``, when you run ``foo`` (by
1756typing ``python foo.py`` as a shell command), a ``.pyc`` will be created for
1757``xyz`` because ``xyz`` is imported, but no ``.pyc`` file will be created for
1758``foo`` since ``foo.py`` isn't being imported.
Georg Brandld7413152009-10-11 21:25:26 +00001759
R David Murrayd913d9d2013-12-13 12:29:29 -05001760If you need to create a ``.pyc`` file for ``foo`` -- that is, to create a
1761``.pyc`` file for a module that is not imported -- you can, using the
1762:mod:`py_compile` and :mod:`compileall` modules.
Georg Brandld7413152009-10-11 21:25:26 +00001763
1764The :mod:`py_compile` module can manually compile any module. One way is to use
1765the ``compile()`` function in that module interactively::
1766
1767 >>> import py_compile
R David Murrayfdf95032013-06-19 16:58:26 -04001768 >>> py_compile.compile('foo.py') # doctest: +SKIP
Georg Brandld7413152009-10-11 21:25:26 +00001769
R David Murrayd913d9d2013-12-13 12:29:29 -05001770This will write the ``.pyc`` to a ``__pycache__`` subdirectory in the same
1771location as ``foo.py`` (or you can override that with the optional parameter
1772``cfile``).
Georg Brandld7413152009-10-11 21:25:26 +00001773
1774You can also automatically compile all files in a directory or directories using
1775the :mod:`compileall` module. You can do it from the shell prompt by running
1776``compileall.py`` and providing the path of a directory containing Python files
1777to compile::
1778
1779 python -m compileall .
1780
1781
1782How do I find the current module name?
1783--------------------------------------
1784
1785A module can find out its own module name by looking at the predefined global
1786variable ``__name__``. If this has the value ``'__main__'``, the program is
1787running as a script. Many modules that are usually used by importing them also
1788provide a command-line interface or a self-test, and only execute this code
1789after checking ``__name__``::
1790
1791 def main():
Georg Brandl62eaaf62009-12-19 17:51:41 +00001792 print('Running test...')
Georg Brandld7413152009-10-11 21:25:26 +00001793 ...
1794
1795 if __name__ == '__main__':
1796 main()
1797
1798
1799How can I have modules that mutually import each other?
1800-------------------------------------------------------
1801
1802Suppose you have the following modules:
1803
1804foo.py::
1805
1806 from bar import bar_var
1807 foo_var = 1
1808
1809bar.py::
1810
1811 from foo import foo_var
1812 bar_var = 2
1813
1814The problem is that the interpreter will perform the following steps:
1815
1816* main imports foo
1817* Empty globals for foo are created
1818* foo is compiled and starts executing
1819* foo imports bar
1820* Empty globals for bar are created
1821* bar is compiled and starts executing
1822* bar imports foo (which is a no-op since there already is a module named foo)
1823* bar.foo_var = foo.foo_var
1824
1825The last step fails, because Python isn't done with interpreting ``foo`` yet and
1826the global symbol dictionary for ``foo`` is still empty.
1827
1828The same thing happens when you use ``import foo``, and then try to access
1829``foo.foo_var`` in global code.
1830
1831There are (at least) three possible workarounds for this problem.
1832
1833Guido van Rossum recommends avoiding all uses of ``from <module> import ...``,
1834and placing all code inside functions. Initializations of global variables and
1835class variables should use constants or built-in functions only. This means
1836everything from an imported module is referenced as ``<module>.<name>``.
1837
1838Jim Roskind suggests performing steps in the following order in each module:
1839
1840* exports (globals, functions, and classes that don't need imported base
1841 classes)
1842* ``import`` statements
1843* active code (including globals that are initialized from imported values).
1844
1845van Rossum doesn't like this approach much because the imports appear in a
1846strange place, but it does work.
1847
1848Matthias Urlichs recommends restructuring your code so that the recursive import
1849is not necessary in the first place.
1850
1851These solutions are not mutually exclusive.
1852
1853
1854__import__('x.y.z') returns <module 'x'>; how do I get z?
1855---------------------------------------------------------
1856
Ezio Melottie4aad5a2014-08-04 19:34:29 +03001857Consider using the convenience function :func:`~importlib.import_module` from
1858:mod:`importlib` instead::
Georg Brandld7413152009-10-11 21:25:26 +00001859
Ezio Melottie4aad5a2014-08-04 19:34:29 +03001860 z = importlib.import_module('x.y.z')
Georg Brandld7413152009-10-11 21:25:26 +00001861
1862
1863When I edit an imported module and reimport it, the changes don't show up. Why does this happen?
1864-------------------------------------------------------------------------------------------------
1865
1866For reasons of efficiency as well as consistency, Python only reads the module
1867file on the first time a module is imported. If it didn't, in a program
1868consisting of many modules where each one imports the same basic module, the
Brett Cannon4f422e32013-06-14 22:49:00 -04001869basic module would be parsed and re-parsed many times. To force re-reading of a
Georg Brandld7413152009-10-11 21:25:26 +00001870changed module, do this::
1871
Brett Cannon4f422e32013-06-14 22:49:00 -04001872 import importlib
Georg Brandld7413152009-10-11 21:25:26 +00001873 import modname
Brett Cannon4f422e32013-06-14 22:49:00 -04001874 importlib.reload(modname)
Georg Brandld7413152009-10-11 21:25:26 +00001875
1876Warning: this technique is not 100% fool-proof. In particular, modules
1877containing statements like ::
1878
1879 from modname import some_objects
1880
1881will continue to work with the old version of the imported objects. If the
1882module contains class definitions, existing class instances will *not* be
1883updated to use the new class definition. This can result in the following
Marco Buttu909a6f62017-03-18 17:59:33 +01001884paradoxical behaviour::
Georg Brandld7413152009-10-11 21:25:26 +00001885
Brett Cannon4f422e32013-06-14 22:49:00 -04001886 >>> import importlib
Georg Brandld7413152009-10-11 21:25:26 +00001887 >>> import cls
1888 >>> c = cls.C() # Create an instance of C
Brett Cannon4f422e32013-06-14 22:49:00 -04001889 >>> importlib.reload(cls)
Georg Brandl62eaaf62009-12-19 17:51:41 +00001890 <module 'cls' from 'cls.py'>
Georg Brandld7413152009-10-11 21:25:26 +00001891 >>> isinstance(c, cls.C) # isinstance is false?!?
1892 False
1893
Georg Brandl62eaaf62009-12-19 17:51:41 +00001894The nature of the problem is made clear if you print out the "identity" of the
Marco Buttu909a6f62017-03-18 17:59:33 +01001895class objects::
Georg Brandld7413152009-10-11 21:25:26 +00001896
Georg Brandl62eaaf62009-12-19 17:51:41 +00001897 >>> hex(id(c.__class__))
1898 '0x7352a0'
1899 >>> hex(id(cls.C))
1900 '0x4198d0'