blob: 2ff7236df1dc0e8e312a9cfdd8e6be27390967d4 [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
Andre Delfinocf48e552019-05-03 13:53:22 -030019Several debuggers for Python are described below, and the built-in function
20:func:`breakpoint` allows you to drop into any of them.
21
Georg Brandld7413152009-10-11 21:25:26 +000022The pdb module is a simple but adequate console-mode debugger for Python. It is
23part of the standard Python library, and is :mod:`documented in the Library
24Reference Manual <pdb>`. You can also write your own debugger by using the code
25for pdb as an example.
26
27The IDLE interactive development environment, which is part of the standard
28Python distribution (normally available as Tools/scripts/idle), includes a
Georg Brandl5e722f62014-10-29 08:55:14 +010029graphical debugger.
Georg Brandld7413152009-10-11 21:25:26 +000030
31PythonWin is a Python IDE that includes a GUI debugger based on pdb. The
32Pythonwin debugger colors breakpoints and has quite a few cool features such as
33debugging non-Pythonwin programs. Pythonwin is available as part of the `Python
Serhiy Storchaka6dff0202016-05-07 10:49:07 +030034for Windows Extensions <https://sourceforge.net/projects/pywin32/>`__ project and
Georg Brandld7413152009-10-11 21:25:26 +000035as a part of the ActivePython distribution (see
Serhiy Storchaka6dff0202016-05-07 10:49:07 +030036https://www.activestate.com/activepython\ ).
Georg Brandld7413152009-10-11 21:25:26 +000037
38`Boa Constructor <http://boa-constructor.sourceforge.net/>`_ is an IDE and GUI
39builder that uses wxWidgets. It offers visual frame creation and manipulation,
40an object inspector, many views on the source like object browsers, inheritance
41hierarchies, doc string generated html documentation, an advanced debugger,
42integrated help, and Zope support.
43
Georg Brandl77fe77d2014-10-29 09:24:54 +010044`Eric <http://eric-ide.python-projects.org/>`_ is an IDE built on PyQt
Georg Brandld7413152009-10-11 21:25:26 +000045and the Scintilla editing component.
46
47Pydb is a version of the standard Python debugger pdb, modified for use with DDD
48(Data Display Debugger), a popular graphical debugger front end. Pydb can be
49found at http://bashdb.sourceforge.net/pydb/ and DDD can be found at
Serhiy Storchaka6dff0202016-05-07 10:49:07 +030050https://www.gnu.org/software/ddd.
Georg Brandld7413152009-10-11 21:25:26 +000051
52There are a number of commercial Python IDEs that include graphical debuggers.
53They include:
54
Serhiy Storchaka6dff0202016-05-07 10:49:07 +030055* Wing IDE (https://wingware.com/)
56* Komodo IDE (https://komodoide.com/)
Georg Brandl5e722f62014-10-29 08:55:14 +010057* PyCharm (https://www.jetbrains.com/pycharm/)
Georg Brandld7413152009-10-11 21:25:26 +000058
59
60Is there a tool to help find bugs or perform static analysis?
61-------------------------------------------------------------
62
63Yes.
64
65PyChecker is a static analysis tool that finds bugs in Python source code and
66warns about code complexity and style. You can get PyChecker from
Georg Brandlb7354a62014-10-29 10:57:37 +010067http://pychecker.sourceforge.net/.
Georg Brandld7413152009-10-11 21:25:26 +000068
Serhiy Storchaka6dff0202016-05-07 10:49:07 +030069`Pylint <https://www.pylint.org/>`_ is another tool that checks
Georg Brandld7413152009-10-11 21:25:26 +000070if a module satisfies a coding standard, and also makes it possible to write
71plug-ins to add a custom feature. In addition to the bug checking that
72PyChecker performs, Pylint offers some additional features such as checking line
73length, whether variable names are well-formed according to your coding
74standard, whether declared interfaces are fully implemented, and more.
Serhiy Storchaka6dff0202016-05-07 10:49:07 +030075https://docs.pylint.org/ provides a full list of Pylint's features.
Georg Brandld7413152009-10-11 21:25:26 +000076
Andrés Delfinoa3782542018-09-11 02:12:41 -030077Static type checkers such as `Mypy <http://mypy-lang.org/>`_,
78`Pyre <https://pyre-check.org/>`_, and
79`Pytype <https://github.com/google/pytype>`_ can check type hints in Python
80source code.
81
Georg Brandld7413152009-10-11 21:25:26 +000082
83How can I create a stand-alone binary from a Python script?
84-----------------------------------------------------------
85
86You don't need the ability to compile Python to C code if all you want is a
87stand-alone program that users can download and run without having to install
88the Python distribution first. There are a number of tools that determine the
89set of modules required by a program and bind these modules together with a
90Python binary to produce a single executable.
91
92One is to use the freeze tool, which is included in the Python source tree as
93``Tools/freeze``. It converts Python byte code to C arrays; a C compiler you can
94embed all your modules into a new program, which is then linked with the
95standard Python modules.
96
97It works by scanning your source recursively for import statements (in both
98forms) and looking for the modules in the standard Python path as well as in the
99source directory (for built-in modules). It then turns the bytecode for modules
100written in Python into C code (array initializers that can be turned into code
101objects using the marshal module) and creates a custom-made config file that
102only contains those built-in modules which are actually used in the program. It
103then compiles the generated C code and links it with the rest of the Python
104interpreter to form a self-contained binary which acts exactly like your script.
105
106Obviously, freeze requires a C compiler. There are several other utilities
107which don't. One is Thomas Heller's py2exe (Windows only) at
108
109 http://www.py2exe.org/
110
Sanyam Khurana1b4587a2017-12-06 22:09:33 +0530111Another tool is Anthony Tuininga's `cx_Freeze <https://anthony-tuininga.github.io/cx_Freeze/>`_.
Georg Brandld7413152009-10-11 21:25:26 +0000112
113
114Are there coding standards or a style guide for Python programs?
115----------------------------------------------------------------
116
117Yes. The coding style required for standard library modules is documented as
118:pep:`8`.
119
120
Georg Brandld7413152009-10-11 21:25:26 +0000121Core Language
122=============
123
R. David Murrayc04a6942009-11-14 22:21:32 +0000124Why am I getting an UnboundLocalError when the variable has a value?
125--------------------------------------------------------------------
Georg Brandld7413152009-10-11 21:25:26 +0000126
R. David Murrayc04a6942009-11-14 22:21:32 +0000127It can be a surprise to get the UnboundLocalError in previously working
128code when it is modified by adding an assignment statement somewhere in
129the body of a function.
Georg Brandld7413152009-10-11 21:25:26 +0000130
R. David Murrayc04a6942009-11-14 22:21:32 +0000131This code:
Georg Brandld7413152009-10-11 21:25:26 +0000132
R. David Murrayc04a6942009-11-14 22:21:32 +0000133 >>> x = 10
134 >>> def bar():
135 ... print(x)
136 >>> bar()
137 10
Georg Brandld7413152009-10-11 21:25:26 +0000138
R. David Murrayc04a6942009-11-14 22:21:32 +0000139works, but this code:
Georg Brandld7413152009-10-11 21:25:26 +0000140
R. David Murrayc04a6942009-11-14 22:21:32 +0000141 >>> x = 10
142 >>> def foo():
143 ... print(x)
144 ... x += 1
Georg Brandld7413152009-10-11 21:25:26 +0000145
R. David Murrayc04a6942009-11-14 22:21:32 +0000146results in an UnboundLocalError:
Georg Brandld7413152009-10-11 21:25:26 +0000147
R. David Murrayc04a6942009-11-14 22:21:32 +0000148 >>> foo()
149 Traceback (most recent call last):
150 ...
151 UnboundLocalError: local variable 'x' referenced before assignment
152
153This is because when you make an assignment to a variable in a scope, that
154variable becomes local to that scope and shadows any similarly named variable
155in the outer scope. Since the last statement in foo assigns a new value to
156``x``, the compiler recognizes it as a local variable. Consequently when the
R. David Murray18163c32009-11-14 22:27:22 +0000157earlier ``print(x)`` attempts to print the uninitialized local variable and
R. David Murrayc04a6942009-11-14 22:21:32 +0000158an error results.
159
160In the example above you can access the outer scope variable by declaring it
161global:
162
163 >>> x = 10
164 >>> def foobar():
165 ... global x
166 ... print(x)
167 ... x += 1
168 >>> foobar()
169 10
170
171This explicit declaration is required in order to remind you that (unlike the
172superficially analogous situation with class and instance variables) you are
173actually modifying the value of the variable in the outer scope:
174
175 >>> print(x)
176 11
177
178You can do a similar thing in a nested scope using the :keyword:`nonlocal`
179keyword:
180
181 >>> def foo():
182 ... x = 10
183 ... def bar():
184 ... nonlocal x
185 ... print(x)
186 ... x += 1
187 ... bar()
188 ... print(x)
189 >>> foo()
190 10
191 11
Georg Brandld7413152009-10-11 21:25:26 +0000192
193
194What are the rules for local and global variables in Python?
195------------------------------------------------------------
196
197In Python, variables that are only referenced inside a function are implicitly
Robert Collinsbd4dd542015-07-30 06:14:32 +1200198global. If a variable is assigned a value anywhere within the function's body,
199it's assumed to be a local unless explicitly declared as global.
Georg Brandld7413152009-10-11 21:25:26 +0000200
201Though a bit surprising at first, a moment's consideration explains this. On
202one hand, requiring :keyword:`global` for assigned variables provides a bar
203against unintended side-effects. On the other hand, if ``global`` was required
204for all global references, you'd be using ``global`` all the time. You'd have
Georg Brandlc4a55fc2010-02-06 18:46:57 +0000205to declare as global every reference to a built-in function or to a component of
Georg Brandld7413152009-10-11 21:25:26 +0000206an imported module. This clutter would defeat the usefulness of the ``global``
207declaration for identifying side-effects.
208
209
Ezio Melotticad8b0f2013-01-05 00:50:46 +0200210Why do lambdas defined in a loop with different values all return the same result?
211----------------------------------------------------------------------------------
212
213Assume you use a for loop to define a few different lambdas (or even plain
214functions), e.g.::
215
R David Murrayfdf95032013-06-19 16:58:26 -0400216 >>> squares = []
217 >>> for x in range(5):
Serhiy Storchakadba90392016-05-10 12:01:23 +0300218 ... squares.append(lambda: x**2)
Ezio Melotticad8b0f2013-01-05 00:50:46 +0200219
220This gives you a list that contains 5 lambdas that calculate ``x**2``. You
221might expect that, when called, they would return, respectively, ``0``, ``1``,
222``4``, ``9``, and ``16``. However, when you actually try you will see that
223they all return ``16``::
224
225 >>> squares[2]()
226 16
227 >>> squares[4]()
228 16
229
230This happens because ``x`` is not local to the lambdas, but is defined in
231the outer scope, and it is accessed when the lambda is called --- not when it
232is defined. At the end of the loop, the value of ``x`` is ``4``, so all the
233functions now return ``4**2``, i.e. ``16``. You can also verify this by
234changing the value of ``x`` and see how the results of the lambdas change::
235
236 >>> x = 8
237 >>> squares[2]()
238 64
239
240In order to avoid this, you need to save the values in variables local to the
241lambdas, so that they don't rely on the value of the global ``x``::
242
R David Murrayfdf95032013-06-19 16:58:26 -0400243 >>> squares = []
244 >>> for x in range(5):
Serhiy Storchakadba90392016-05-10 12:01:23 +0300245 ... squares.append(lambda n=x: n**2)
Ezio Melotticad8b0f2013-01-05 00:50:46 +0200246
247Here, ``n=x`` creates a new variable ``n`` local to the lambda and computed
248when the lambda is defined so that it has the same value that ``x`` had at
249that point in the loop. This means that the value of ``n`` will be ``0``
250in the first lambda, ``1`` in the second, ``2`` in the third, and so on.
251Therefore each lambda will now return the correct result::
252
253 >>> squares[2]()
254 4
255 >>> squares[4]()
256 16
257
258Note that this behaviour is not peculiar to lambdas, but applies to regular
259functions too.
260
261
Georg Brandld7413152009-10-11 21:25:26 +0000262How do I share global variables across modules?
263------------------------------------------------
264
265The canonical way to share information across modules within a single program is
266to create a special module (often called config or cfg). Just import the config
267module in all modules of your application; the module then becomes available as
268a global name. Because there is only one instance of each module, any changes
269made to the module object get reflected everywhere. For example:
270
271config.py::
272
273 x = 0 # Default value of the 'x' configuration setting
274
275mod.py::
276
277 import config
278 config.x = 1
279
280main.py::
281
282 import config
283 import mod
Georg Brandl62eaaf62009-12-19 17:51:41 +0000284 print(config.x)
Georg Brandld7413152009-10-11 21:25:26 +0000285
286Note that using a module is also the basis for implementing the Singleton design
287pattern, for the same reason.
288
289
290What are the "best practices" for using import in a module?
291-----------------------------------------------------------
292
293In general, don't use ``from modulename import *``. Doing so clutters the
Georg Brandla94ad1e2014-10-06 16:02:09 +0200294importer's namespace, and makes it much harder for linters to detect undefined
295names.
Georg Brandld7413152009-10-11 21:25:26 +0000296
297Import modules at the top of a file. Doing so makes it clear what other modules
298your code requires and avoids questions of whether the module name is in scope.
299Using one import per line makes it easy to add and delete module imports, but
300using multiple imports per line uses less screen space.
301
302It's good practice if you import modules in the following order:
303
Georg Brandl62eaaf62009-12-19 17:51:41 +00003041. standard library modules -- e.g. ``sys``, ``os``, ``getopt``, ``re``
Georg Brandld7413152009-10-11 21:25:26 +00003052. third-party library modules (anything installed in Python's site-packages
306 directory) -- e.g. mx.DateTime, ZODB, PIL.Image, etc.
3073. locally-developed modules
308
Georg Brandld7413152009-10-11 21:25:26 +0000309It is sometimes necessary to move imports to a function or class to avoid
310problems with circular imports. Gordon McMillan says:
311
312 Circular imports are fine where both modules use the "import <module>" form
313 of import. They fail when the 2nd module wants to grab a name out of the
314 first ("from module import name") and the import is at the top level. That's
315 because names in the 1st are not yet available, because the first module is
316 busy importing the 2nd.
317
318In this case, if the second module is only used in one function, then the import
319can easily be moved into that function. By the time the import is called, the
320first module will have finished initializing, and the second module can do its
321import.
322
323It may also be necessary to move imports out of the top level of code if some of
324the modules are platform-specific. In that case, it may not even be possible to
325import all of the modules at the top of the file. In this case, importing the
326correct modules in the corresponding platform-specific code is a good option.
327
328Only move imports into a local scope, such as inside a function definition, if
329it's necessary to solve a problem such as avoiding a circular import or are
330trying to reduce the initialization time of a module. This technique is
331especially helpful if many of the imports are unnecessary depending on how the
332program executes. You may also want to move imports into a function if the
333modules are only ever used in that function. Note that loading a module the
334first time may be expensive because of the one time initialization of the
335module, but loading a module multiple times is virtually free, costing only a
336couple of dictionary lookups. Even if the module name has gone out of scope,
337the module is probably available in :data:`sys.modules`.
338
Georg Brandld7413152009-10-11 21:25:26 +0000339
Ezio Melotti898eb822014-07-06 20:53:27 +0300340Why are default values shared between objects?
341----------------------------------------------
342
343This type of bug commonly bites neophyte programmers. Consider this function::
344
345 def foo(mydict={}): # Danger: shared reference to one dict for all calls
346 ... compute something ...
347 mydict[key] = value
348 return mydict
349
350The first time you call this function, ``mydict`` contains a single item. The
351second time, ``mydict`` contains two items because when ``foo()`` begins
352executing, ``mydict`` starts out with an item already in it.
353
354It is often expected that a function call creates new objects for default
355values. This is not what happens. Default values are created exactly once, when
356the function is defined. If that object is changed, like the dictionary in this
357example, subsequent calls to the function will refer to this changed object.
358
359By definition, immutable objects such as numbers, strings, tuples, and ``None``,
360are safe from change. Changes to mutable objects such as dictionaries, lists,
361and class instances can lead to confusion.
362
363Because of this feature, it is good programming practice to not use mutable
364objects as default values. Instead, use ``None`` as the default value and
365inside the function, check if the parameter is ``None`` and create a new
366list/dictionary/whatever if it is. For example, don't write::
367
368 def foo(mydict={}):
369 ...
370
371but::
372
373 def foo(mydict=None):
374 if mydict is None:
375 mydict = {} # create a new dict for local namespace
376
377This feature can be useful. When you have a function that's time-consuming to
378compute, a common technique is to cache the parameters and the resulting value
379of each call to the function, and return the cached value if the same value is
380requested again. This is called "memoizing", and can be implemented like this::
381
Noah Haasis2707e412018-06-16 05:29:11 +0200382 # Callers can only provide two parameters and optionally pass _cache by keyword
383 def expensive(arg1, arg2, *, _cache={}):
Ezio Melotti898eb822014-07-06 20:53:27 +0300384 if (arg1, arg2) in _cache:
385 return _cache[(arg1, arg2)]
386
387 # Calculate the value
388 result = ... expensive computation ...
R David Murray623ae292014-09-28 11:01:11 -0400389 _cache[(arg1, arg2)] = result # Store result in the cache
Ezio Melotti898eb822014-07-06 20:53:27 +0300390 return result
391
392You could use a global variable containing a dictionary instead of the default
393value; it's a matter of taste.
394
395
Georg Brandld7413152009-10-11 21:25:26 +0000396How can I pass optional or keyword parameters from one function to another?
397---------------------------------------------------------------------------
398
399Collect the arguments using the ``*`` and ``**`` specifiers in the function's
400parameter list; this gives you the positional arguments as a tuple and the
401keyword arguments as a dictionary. You can then pass these arguments when
402calling another function by using ``*`` and ``**``::
403
404 def f(x, *args, **kwargs):
405 ...
406 kwargs['width'] = '14.3c'
407 ...
408 g(x, *args, **kwargs)
409
Georg Brandld7413152009-10-11 21:25:26 +0000410
Chris Jerdonekb4309942012-12-25 14:54:44 -0800411.. index::
412 single: argument; difference from parameter
413 single: parameter; difference from argument
414
Chris Jerdonekc2a7fd62012-11-28 02:29:33 -0800415.. _faq-argument-vs-parameter:
416
417What is the difference between arguments and parameters?
418--------------------------------------------------------
419
420:term:`Parameters <parameter>` are defined by the names that appear in a
421function definition, whereas :term:`arguments <argument>` are the values
422actually passed to a function when calling it. Parameters define what types of
423arguments a function can accept. For example, given the function definition::
424
425 def func(foo, bar=None, **kwargs):
426 pass
427
428*foo*, *bar* and *kwargs* are parameters of ``func``. However, when calling
429``func``, for example::
430
431 func(42, bar=314, extra=somevar)
432
433the values ``42``, ``314``, and ``somevar`` are arguments.
434
435
R David Murray623ae292014-09-28 11:01:11 -0400436Why did changing list 'y' also change list 'x'?
437------------------------------------------------
438
439If you wrote code like::
440
441 >>> x = []
442 >>> y = x
443 >>> y.append(10)
444 >>> y
445 [10]
446 >>> x
447 [10]
448
449you might be wondering why appending an element to ``y`` changed ``x`` too.
450
451There are two factors that produce this result:
452
4531) Variables are simply names that refer to objects. Doing ``y = x`` doesn't
454 create a copy of the list -- it creates a new variable ``y`` that refers to
455 the same object ``x`` refers to. This means that there is only one object
456 (the list), and both ``x`` and ``y`` refer to it.
4572) Lists are :term:`mutable`, which means that you can change their content.
458
459After the call to :meth:`~list.append`, the content of the mutable object has
460changed from ``[]`` to ``[10]``. Since both the variables refer to the same
R David Murray12dc0d92014-09-29 10:17:28 -0400461object, using either name accesses the modified value ``[10]``.
R David Murray623ae292014-09-28 11:01:11 -0400462
463If we instead assign an immutable object to ``x``::
464
465 >>> x = 5 # ints are immutable
466 >>> y = x
467 >>> x = x + 1 # 5 can't be mutated, we are creating a new object here
468 >>> x
469 6
470 >>> y
471 5
472
473we can see that in this case ``x`` and ``y`` are not equal anymore. This is
474because integers are :term:`immutable`, and when we do ``x = x + 1`` we are not
475mutating the int ``5`` by incrementing its value; instead, we are creating a
476new object (the int ``6``) and assigning it to ``x`` (that is, changing which
477object ``x`` refers to). After this assignment we have two objects (the ints
478``6`` and ``5``) and two variables that refer to them (``x`` now refers to
479``6`` but ``y`` still refers to ``5``).
480
481Some operations (for example ``y.append(10)`` and ``y.sort()``) mutate the
482object, whereas superficially similar operations (for example ``y = y + [10]``
483and ``sorted(y)``) create a new object. In general in Python (and in all cases
484in the standard library) a method that mutates an object will return ``None``
485to help avoid getting the two types of operations confused. So if you
486mistakenly write ``y.sort()`` thinking it will give you a sorted copy of ``y``,
487you'll instead end up with ``None``, which will likely cause your program to
488generate an easily diagnosed error.
489
490However, there is one class of operations where the same operation sometimes
491has different behaviors with different types: the augmented assignment
492operators. For example, ``+=`` mutates lists but not tuples or ints (``a_list
493+= [1, 2, 3]`` is equivalent to ``a_list.extend([1, 2, 3])`` and mutates
494``a_list``, whereas ``some_tuple += (1, 2, 3)`` and ``some_int += 1`` create
495new objects).
496
497In other words:
498
499* If we have a mutable object (:class:`list`, :class:`dict`, :class:`set`,
500 etc.), we can use some specific operations to mutate it and all the variables
501 that refer to it will see the change.
502* If we have an immutable object (:class:`str`, :class:`int`, :class:`tuple`,
503 etc.), all the variables that refer to it will always see the same value,
504 but operations that transform that value into a new value always return a new
505 object.
506
507If you want to know if two variables refer to the same object or not, you can
508use the :keyword:`is` operator, or the built-in function :func:`id`.
509
510
Georg Brandld7413152009-10-11 21:25:26 +0000511How do I write a function with output parameters (call by reference)?
512---------------------------------------------------------------------
513
514Remember that arguments are passed by assignment in Python. Since assignment
515just creates references to objects, there's no alias between an argument name in
516the caller and callee, and so no call-by-reference per se. You can achieve the
517desired effect in a number of ways.
518
5191) By returning a tuple of the results::
520
521 def func2(a, b):
522 a = 'new-value' # a and b are local names
523 b = b + 1 # assigned to new objects
524 return a, b # return new values
525
526 x, y = 'old-value', 99
527 x, y = func2(x, y)
Georg Brandl62eaaf62009-12-19 17:51:41 +0000528 print(x, y) # output: new-value 100
Georg Brandld7413152009-10-11 21:25:26 +0000529
530 This is almost always the clearest solution.
531
5322) By using global variables. This isn't thread-safe, and is not recommended.
533
5343) By passing a mutable (changeable in-place) object::
535
536 def func1(a):
537 a[0] = 'new-value' # 'a' references a mutable list
538 a[1] = a[1] + 1 # changes a shared object
539
540 args = ['old-value', 99]
541 func1(args)
Georg Brandl62eaaf62009-12-19 17:51:41 +0000542 print(args[0], args[1]) # output: new-value 100
Georg Brandld7413152009-10-11 21:25:26 +0000543
5444) By passing in a dictionary that gets mutated::
545
546 def func3(args):
547 args['a'] = 'new-value' # args is a mutable dictionary
548 args['b'] = args['b'] + 1 # change it in-place
549
Serhiy Storchakadba90392016-05-10 12:01:23 +0300550 args = {'a': 'old-value', 'b': 99}
Georg Brandld7413152009-10-11 21:25:26 +0000551 func3(args)
Georg Brandl62eaaf62009-12-19 17:51:41 +0000552 print(args['a'], args['b'])
Georg Brandld7413152009-10-11 21:25:26 +0000553
5545) Or bundle up values in a class instance::
555
556 class callByRef:
Serhiy Storchaka70c5f2a2019-06-01 11:38:24 +0300557 def __init__(self, /, **args):
558 for key, value in args.items():
Georg Brandld7413152009-10-11 21:25:26 +0000559 setattr(self, key, value)
560
561 def func4(args):
562 args.a = 'new-value' # args is a mutable callByRef
563 args.b = args.b + 1 # change object in-place
564
565 args = callByRef(a='old-value', b=99)
566 func4(args)
Georg Brandl62eaaf62009-12-19 17:51:41 +0000567 print(args.a, args.b)
Georg Brandld7413152009-10-11 21:25:26 +0000568
569
570 There's almost never a good reason to get this complicated.
571
572Your best choice is to return a tuple containing the multiple results.
573
574
575How do you make a higher order function in Python?
576--------------------------------------------------
577
578You have two choices: you can use nested scopes or you can use callable objects.
579For example, suppose you wanted to define ``linear(a,b)`` which returns a
580function ``f(x)`` that computes the value ``a*x+b``. Using nested scopes::
581
582 def linear(a, b):
583 def result(x):
584 return a * x + b
585 return result
586
587Or using a callable object::
588
589 class linear:
590
591 def __init__(self, a, b):
592 self.a, self.b = a, b
593
594 def __call__(self, x):
595 return self.a * x + self.b
596
597In both cases, ::
598
599 taxes = linear(0.3, 2)
600
601gives a callable object where ``taxes(10e6) == 0.3 * 10e6 + 2``.
602
603The callable object approach has the disadvantage that it is a bit slower and
604results in slightly longer code. However, note that a collection of callables
605can share their signature via inheritance::
606
607 class exponential(linear):
608 # __init__ inherited
609 def __call__(self, x):
610 return self.a * (x ** self.b)
611
612Object can encapsulate state for several methods::
613
614 class counter:
615
616 value = 0
617
618 def set(self, x):
619 self.value = x
620
621 def up(self):
622 self.value = self.value + 1
623
624 def down(self):
625 self.value = self.value - 1
626
627 count = counter()
628 inc, dec, reset = count.up, count.down, count.set
629
630Here ``inc()``, ``dec()`` and ``reset()`` act like functions which share the
631same counting variable.
632
633
634How do I copy an object in Python?
635----------------------------------
636
637In general, try :func:`copy.copy` or :func:`copy.deepcopy` for the general case.
638Not all objects can be copied, but most can.
639
640Some objects can be copied more easily. Dictionaries have a :meth:`~dict.copy`
641method::
642
643 newdict = olddict.copy()
644
645Sequences can be copied by slicing::
646
647 new_l = l[:]
648
649
650How can I find the methods or attributes of an object?
651------------------------------------------------------
652
653For an instance x of a user-defined class, ``dir(x)`` returns an alphabetized
654list of the names containing the instance attributes and methods and attributes
655defined by its class.
656
657
658How can my code discover the name of an object?
659-----------------------------------------------
660
661Generally speaking, it can't, because objects don't really have names.
avinassh3aa48b82019-08-29 11:10:50 +0530662Essentially, assignment always binds a name to a value; the same is true of
Georg Brandld7413152009-10-11 21:25:26 +0000663``def`` and ``class`` statements, but in that case the value is a
664callable. Consider the following code::
665
Serhiy Storchakadba90392016-05-10 12:01:23 +0300666 >>> class A:
667 ... pass
668 ...
669 >>> B = A
670 >>> a = B()
671 >>> b = a
672 >>> print(b)
Georg Brandl62eaaf62009-12-19 17:51:41 +0000673 <__main__.A object at 0x16D07CC>
Serhiy Storchakadba90392016-05-10 12:01:23 +0300674 >>> print(a)
Georg Brandl62eaaf62009-12-19 17:51:41 +0000675 <__main__.A object at 0x16D07CC>
Georg Brandld7413152009-10-11 21:25:26 +0000676
677Arguably the class has a name: even though it is bound to two names and invoked
678through the name B the created instance is still reported as an instance of
679class A. However, it is impossible to say whether the instance's name is a or
680b, since both names are bound to the same value.
681
682Generally speaking it should not be necessary for your code to "know the names"
683of particular values. Unless you are deliberately writing introspective
684programs, this is usually an indication that a change of approach might be
685beneficial.
686
687In comp.lang.python, Fredrik Lundh once gave an excellent analogy in answer to
688this question:
689
690 The same way as you get the name of that cat you found on your porch: the cat
691 (object) itself cannot tell you its name, and it doesn't really care -- so
692 the only way to find out what it's called is to ask all your neighbours
693 (namespaces) if it's their cat (object)...
694
695 ....and don't be surprised if you'll find that it's known by many names, or
696 no name at all!
697
698
699What's up with the comma operator's precedence?
700-----------------------------------------------
701
702Comma is not an operator in Python. Consider this session::
703
704 >>> "a" in "b", "a"
Georg Brandl62eaaf62009-12-19 17:51:41 +0000705 (False, 'a')
Georg Brandld7413152009-10-11 21:25:26 +0000706
707Since the comma is not an operator, but a separator between expressions the
708above is evaluated as if you had entered::
709
R David Murrayfdf95032013-06-19 16:58:26 -0400710 ("a" in "b"), "a"
Georg Brandld7413152009-10-11 21:25:26 +0000711
712not::
713
R David Murrayfdf95032013-06-19 16:58:26 -0400714 "a" in ("b", "a")
Georg Brandld7413152009-10-11 21:25:26 +0000715
716The same is true of the various assignment operators (``=``, ``+=`` etc). They
717are not truly operators but syntactic delimiters in assignment statements.
718
719
720Is there an equivalent of C's "?:" ternary operator?
721----------------------------------------------------
722
Antoine Pitrouc5b266e2011-12-03 22:11:11 +0100723Yes, there is. The syntax is as follows::
Georg Brandld7413152009-10-11 21:25:26 +0000724
725 [on_true] if [expression] else [on_false]
726
727 x, y = 50, 25
Georg Brandld7413152009-10-11 21:25:26 +0000728 small = x if x < y else y
729
Antoine Pitrouc5b266e2011-12-03 22:11:11 +0100730Before this syntax was introduced in Python 2.5, a common idiom was to use
731logical operators::
Georg Brandld7413152009-10-11 21:25:26 +0000732
Antoine Pitrouc5b266e2011-12-03 22:11:11 +0100733 [expression] and [on_true] or [on_false]
Georg Brandld7413152009-10-11 21:25:26 +0000734
Antoine Pitrouc5b266e2011-12-03 22:11:11 +0100735However, this idiom is unsafe, as it can give wrong results when *on_true*
736has a false boolean value. Therefore, it is always better to use
737the ``... if ... else ...`` form.
Georg Brandld7413152009-10-11 21:25:26 +0000738
739
740Is it possible to write obfuscated one-liners in Python?
741--------------------------------------------------------
742
743Yes. Usually this is done by nesting :keyword:`lambda` within
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200744:keyword:`!lambda`. See the following three examples, due to Ulf Bartelt::
Georg Brandld7413152009-10-11 21:25:26 +0000745
Georg Brandl62eaaf62009-12-19 17:51:41 +0000746 from functools import reduce
747
Georg Brandld7413152009-10-11 21:25:26 +0000748 # Primes < 1000
Georg Brandl62eaaf62009-12-19 17:51:41 +0000749 print(list(filter(None,map(lambda y:y*reduce(lambda x,y:x*y!=0,
750 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 +0000751
752 # First 10 Fibonacci numbers
Georg Brandl62eaaf62009-12-19 17:51:41 +0000753 print(list(map(lambda x,f=lambda x,f:(f(x-1,f)+f(x-2,f)) if x>1 else 1:
754 f(x,f), range(10))))
Georg Brandld7413152009-10-11 21:25:26 +0000755
756 # Mandelbrot set
Georg Brandl62eaaf62009-12-19 17:51:41 +0000757 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 +0000758 Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,Sy=Sy,L=lambda yc,Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,i=IM,
759 Sx=Sx,Sy=Sy:reduce(lambda x,y:x+y,map(lambda x,xc=Ru,yc=yc,Ru=Ru,Ro=Ro,
760 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
761 >=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(
762 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 +0000763 ))))(-2.1, 0.7, -1.2, 1.2, 30, 80, 24))
Georg Brandld7413152009-10-11 21:25:26 +0000764 # \___ ___/ \___ ___/ | | |__ lines on screen
765 # V V | |______ columns on screen
766 # | | |__________ maximum of "iterations"
767 # | |_________________ range on y axis
768 # |____________________________ range on x axis
769
770Don't try this at home, kids!
771
772
Lysandros Nikolaou1aeeaeb2019-03-10 12:30:11 +0100773.. _faq-positional-only-arguments:
774
775What does the slash(/) in the parameter list of a function mean?
776----------------------------------------------------------------
777
778A slash in the argument list of a function denotes that the parameters prior to
779it are positional-only. Positional-only parameters are the ones without an
780externally-usable name. Upon calling a function that accepts positional-only
781parameters, arguments are mapped to parameters based solely on their position.
782For example, :func:`pow` is a function that accepts positional-only parameters.
783Its documentation looks like this::
784
785 >>> help(pow)
786 Help on built-in function pow in module builtins:
787
788 pow(x, y, z=None, /)
789 Equivalent to x**y (with two arguments) or x**y % z (with three arguments)
790
791 Some types, such as ints, are able to use a more efficient algorithm when
792 invoked using the three argument form.
793
794The slash at the end of the parameter list means that all three parameters are
Xtreak9b5a0ef2019-05-16 10:04:24 +0530795positional-only. Thus, calling :func:`pow` with keyword arguments would lead to
Lysandros Nikolaou1aeeaeb2019-03-10 12:30:11 +0100796an error::
797
798 >>> pow(x=3, y=4)
799 Traceback (most recent call last):
800 File "<stdin>", line 1, in <module>
801 TypeError: pow() takes no keyword arguments
802
Lysandros Nikolaou1aeeaeb2019-03-10 12:30:11 +0100803
Georg Brandld7413152009-10-11 21:25:26 +0000804Numbers and strings
805===================
806
807How do I specify hexadecimal and octal integers?
808------------------------------------------------
809
Georg Brandl62eaaf62009-12-19 17:51:41 +0000810To specify an octal digit, precede the octal value with a zero, and then a lower
811or uppercase "o". For example, to set the variable "a" to the octal value "10"
812(8 in decimal), type::
Georg Brandld7413152009-10-11 21:25:26 +0000813
Georg Brandl62eaaf62009-12-19 17:51:41 +0000814 >>> a = 0o10
Georg Brandld7413152009-10-11 21:25:26 +0000815 >>> a
816 8
817
818Hexadecimal is just as easy. Simply precede the hexadecimal number with a zero,
819and then a lower or uppercase "x". Hexadecimal digits can be specified in lower
820or uppercase. For example, in the Python interpreter::
821
822 >>> a = 0xa5
823 >>> a
824 165
825 >>> b = 0XB2
826 >>> b
827 178
828
829
Georg Brandl62eaaf62009-12-19 17:51:41 +0000830Why does -22 // 10 return -3?
831-----------------------------
Georg Brandld7413152009-10-11 21:25:26 +0000832
833It's primarily driven by the desire that ``i % j`` have the same sign as ``j``.
834If you want that, and also want::
835
Georg Brandl62eaaf62009-12-19 17:51:41 +0000836 i == (i // j) * j + (i % j)
Georg Brandld7413152009-10-11 21:25:26 +0000837
838then integer division has to return the floor. C also requires that identity to
Georg Brandl62eaaf62009-12-19 17:51:41 +0000839hold, and then compilers that truncate ``i // j`` need to make ``i % j`` have
840the same sign as ``i``.
Georg Brandld7413152009-10-11 21:25:26 +0000841
842There are few real use cases for ``i % j`` when ``j`` is negative. When ``j``
843is positive, there are many, and in virtually all of them it's more useful for
844``i % j`` to be ``>= 0``. If the clock says 10 now, what did it say 200 hours
845ago? ``-190 % 12 == 2`` is useful; ``-190 % 12 == -10`` is a bug waiting to
846bite.
847
848
849How do I convert a string to a number?
850--------------------------------------
851
852For integers, use the built-in :func:`int` type constructor, e.g. ``int('144')
853== 144``. Similarly, :func:`float` converts to floating-point,
854e.g. ``float('144') == 144.0``.
855
856By default, these interpret the number as decimal, so that ``int('0144') ==
857144`` and ``int('0x144')`` raises :exc:`ValueError`. ``int(string, base)`` takes
858the base to convert from as a second optional argument, so ``int('0x144', 16) ==
859324``. If the base is specified as 0, the number is interpreted using Python's
Eric V. Smithfc9a4d82014-04-14 07:41:52 -0400860rules: a leading '0o' indicates octal, and '0x' indicates a hex number.
Georg Brandld7413152009-10-11 21:25:26 +0000861
862Do not use the built-in function :func:`eval` if all you need is to convert
863strings to numbers. :func:`eval` will be significantly slower and it presents a
864security risk: someone could pass you a Python expression that might have
865unwanted side effects. For example, someone could pass
866``__import__('os').system("rm -rf $HOME")`` which would erase your home
867directory.
868
869:func:`eval` also has the effect of interpreting numbers as Python expressions,
Georg Brandl62eaaf62009-12-19 17:51:41 +0000870so that e.g. ``eval('09')`` gives a syntax error because Python does not allow
871leading '0' in a decimal number (except '0').
Georg Brandld7413152009-10-11 21:25:26 +0000872
873
874How do I convert a number to a string?
875--------------------------------------
876
877To convert, e.g., the number 144 to the string '144', use the built-in type
878constructor :func:`str`. If you want a hexadecimal or octal representation, use
Georg Brandl62eaaf62009-12-19 17:51:41 +0000879the built-in functions :func:`hex` or :func:`oct`. For fancy formatting, see
Martin Panterbc1ee462016-02-13 00:41:37 +0000880the :ref:`f-strings` and :ref:`formatstrings` sections,
881e.g. ``"{:04d}".format(144)`` yields
Eric V. Smith04d8a242014-04-14 07:52:53 -0400882``'0144'`` and ``"{:.3f}".format(1.0/3.0)`` yields ``'0.333'``.
Georg Brandld7413152009-10-11 21:25:26 +0000883
884
885How do I modify a string in place?
886----------------------------------
887
Antoine Pitrouc5b266e2011-12-03 22:11:11 +0100888You can't, because strings are immutable. In most situations, you should
889simply construct a new string from the various parts you want to assemble
890it from. However, if you need an object with the ability to modify in-place
Martin Panter7462b6492015-11-02 03:37:02 +0000891unicode data, try using an :class:`io.StringIO` object or the :mod:`array`
Antoine Pitrouc5b266e2011-12-03 22:11:11 +0100892module::
Georg Brandld7413152009-10-11 21:25:26 +0000893
R David Murrayfdf95032013-06-19 16:58:26 -0400894 >>> import io
Georg Brandld7413152009-10-11 21:25:26 +0000895 >>> s = "Hello, world"
Antoine Pitrouc5b266e2011-12-03 22:11:11 +0100896 >>> sio = io.StringIO(s)
897 >>> sio.getvalue()
898 'Hello, world'
899 >>> sio.seek(7)
900 7
901 >>> sio.write("there!")
902 6
903 >>> sio.getvalue()
Georg Brandld7413152009-10-11 21:25:26 +0000904 'Hello, there!'
905
906 >>> import array
Georg Brandl62eaaf62009-12-19 17:51:41 +0000907 >>> a = array.array('u', s)
908 >>> print(a)
909 array('u', 'Hello, world')
910 >>> a[0] = 'y'
911 >>> print(a)
R David Murrayfdf95032013-06-19 16:58:26 -0400912 array('u', 'yello, world')
Georg Brandl62eaaf62009-12-19 17:51:41 +0000913 >>> a.tounicode()
Georg Brandld7413152009-10-11 21:25:26 +0000914 'yello, world'
915
916
917How do I use strings to call functions/methods?
918-----------------------------------------------
919
920There are various techniques.
921
922* The best is to use a dictionary that maps strings to functions. The primary
923 advantage of this technique is that the strings do not need to match the names
924 of the functions. This is also the primary technique used to emulate a case
925 construct::
926
927 def a():
928 pass
929
930 def b():
931 pass
932
933 dispatch = {'go': a, 'stop': b} # Note lack of parens for funcs
934
935 dispatch[get_input()]() # Note trailing parens to call function
936
937* Use the built-in function :func:`getattr`::
938
939 import foo
940 getattr(foo, 'bar')()
941
942 Note that :func:`getattr` works on any object, including classes, class
943 instances, modules, and so on.
944
945 This is used in several places in the standard library, like this::
946
947 class Foo:
948 def do_foo(self):
949 ...
950
951 def do_bar(self):
952 ...
953
954 f = getattr(foo_instance, 'do_' + opname)
955 f()
956
957
958* Use :func:`locals` or :func:`eval` to resolve the function name::
959
960 def myFunc():
Georg Brandl62eaaf62009-12-19 17:51:41 +0000961 print("hello")
Georg Brandld7413152009-10-11 21:25:26 +0000962
963 fname = "myFunc"
964
965 f = locals()[fname]
966 f()
967
968 f = eval(fname)
969 f()
970
971 Note: Using :func:`eval` is slow and dangerous. If you don't have absolute
972 control over the contents of the string, someone could pass a string that
973 resulted in an arbitrary function being executed.
974
975Is there an equivalent to Perl's chomp() for removing trailing newlines from strings?
976-------------------------------------------------------------------------------------
977
Antoine Pitrouf3520402011-12-03 22:19:55 +0100978You can use ``S.rstrip("\r\n")`` to remove all occurrences of any line
979terminator from the end of the string ``S`` without removing other trailing
980whitespace. If the string ``S`` represents more than one line, with several
981empty lines at the end, the line terminators for all the blank lines will
982be removed::
Georg Brandld7413152009-10-11 21:25:26 +0000983
984 >>> lines = ("line 1 \r\n"
985 ... "\r\n"
986 ... "\r\n")
987 >>> lines.rstrip("\n\r")
Georg Brandl62eaaf62009-12-19 17:51:41 +0000988 'line 1 '
Georg Brandld7413152009-10-11 21:25:26 +0000989
990Since this is typically only desired when reading text one line at a time, using
991``S.rstrip()`` this way works well.
992
Georg Brandld7413152009-10-11 21:25:26 +0000993
994Is there a scanf() or sscanf() equivalent?
995------------------------------------------
996
997Not as such.
998
999For simple input parsing, the easiest approach is usually to split the line into
1000whitespace-delimited words using the :meth:`~str.split` method of string objects
1001and then convert decimal strings to numeric values using :func:`int` or
1002:func:`float`. ``split()`` supports an optional "sep" parameter which is useful
1003if the line uses something other than whitespace as a separator.
1004
Brian Curtin5a7a52f2010-09-23 13:45:21 +00001005For more complicated input parsing, regular expressions are more powerful
Georg Brandl60203b42010-10-06 10:11:56 +00001006than C's :c:func:`sscanf` and better suited for the task.
Georg Brandld7413152009-10-11 21:25:26 +00001007
1008
Georg Brandl62eaaf62009-12-19 17:51:41 +00001009What does 'UnicodeDecodeError' or 'UnicodeEncodeError' error mean?
1010-------------------------------------------------------------------
Georg Brandld7413152009-10-11 21:25:26 +00001011
Georg Brandl62eaaf62009-12-19 17:51:41 +00001012See the :ref:`unicode-howto`.
Georg Brandld7413152009-10-11 21:25:26 +00001013
1014
Antoine Pitrou432259f2011-12-09 23:10:31 +01001015Performance
1016===========
1017
1018My program is too slow. How do I speed it up?
1019---------------------------------------------
1020
1021That's a tough one, in general. First, here are a list of things to
1022remember before diving further:
1023
Georg Brandl300a6912012-03-14 22:40:08 +01001024* Performance characteristics vary across Python implementations. This FAQ
Antoine Pitrou432259f2011-12-09 23:10:31 +01001025 focusses on :term:`CPython`.
Georg Brandl300a6912012-03-14 22:40:08 +01001026* Behaviour can vary across operating systems, especially when talking about
Antoine Pitrou432259f2011-12-09 23:10:31 +01001027 I/O or multi-threading.
1028* You should always find the hot spots in your program *before* attempting to
1029 optimize any code (see the :mod:`profile` module).
1030* Writing benchmark scripts will allow you to iterate quickly when searching
1031 for improvements (see the :mod:`timeit` module).
1032* It is highly recommended to have good code coverage (through unit testing
1033 or any other technique) before potentially introducing regressions hidden
1034 in sophisticated optimizations.
1035
1036That being said, there are many tricks to speed up Python code. Here are
1037some general principles which go a long way towards reaching acceptable
1038performance levels:
1039
1040* Making your algorithms faster (or changing to faster ones) can yield
1041 much larger benefits than trying to sprinkle micro-optimization tricks
1042 all over your code.
1043
1044* Use the right data structures. Study documentation for the :ref:`bltin-types`
1045 and the :mod:`collections` module.
1046
1047* When the standard library provides a primitive for doing something, it is
1048 likely (although not guaranteed) to be faster than any alternative you
1049 may come up with. This is doubly true for primitives written in C, such
1050 as builtins and some extension types. For example, be sure to use
1051 either the :meth:`list.sort` built-in method or the related :func:`sorted`
Senthil Kumarand03d1d42016-01-01 23:25:58 -08001052 function to do sorting (and see the :ref:`sortinghowto` for examples
Antoine Pitrou432259f2011-12-09 23:10:31 +01001053 of moderately advanced usage).
1054
1055* Abstractions tend to create indirections and force the interpreter to work
1056 more. If the levels of indirection outweigh the amount of useful work
1057 done, your program will be slower. You should avoid excessive abstraction,
1058 especially under the form of tiny functions or methods (which are also often
1059 detrimental to readability).
1060
1061If you have reached the limit of what pure Python can allow, there are tools
1062to take you further away. For example, `Cython <http://cython.org>`_ can
1063compile a slightly modified version of Python code into a C extension, and
1064can be used on many different platforms. Cython can take advantage of
1065compilation (and optional type annotations) to make your code significantly
1066faster than when interpreted. If you are confident in your C programming
1067skills, you can also :ref:`write a C extension module <extending-index>`
1068yourself.
1069
1070.. seealso::
1071 The wiki page devoted to `performance tips
Georg Brandle73778c2014-10-29 08:36:35 +01001072 <https://wiki.python.org/moin/PythonSpeed/PerformanceTips>`_.
Antoine Pitrou432259f2011-12-09 23:10:31 +01001073
1074.. _efficient_string_concatenation:
1075
Antoine Pitroufd9ebd42011-11-25 16:33:53 +01001076What is the most efficient way to concatenate many strings together?
1077--------------------------------------------------------------------
1078
1079:class:`str` and :class:`bytes` objects are immutable, therefore concatenating
1080many strings together is inefficient as each concatenation creates a new
1081object. In the general case, the total runtime cost is quadratic in the
1082total string length.
1083
1084To accumulate many :class:`str` objects, the recommended idiom is to place
1085them into a list and call :meth:`str.join` at the end::
1086
1087 chunks = []
1088 for s in my_strings:
1089 chunks.append(s)
1090 result = ''.join(chunks)
1091
1092(another reasonably efficient idiom is to use :class:`io.StringIO`)
1093
1094To accumulate many :class:`bytes` objects, the recommended idiom is to extend
1095a :class:`bytearray` object using in-place concatenation (the ``+=`` operator)::
1096
1097 result = bytearray()
1098 for b in my_bytes_objects:
1099 result += b
1100
1101
Georg Brandld7413152009-10-11 21:25:26 +00001102Sequences (Tuples/Lists)
1103========================
1104
1105How do I convert between tuples and lists?
1106------------------------------------------
1107
1108The type constructor ``tuple(seq)`` converts any sequence (actually, any
1109iterable) into a tuple with the same items in the same order.
1110
1111For example, ``tuple([1, 2, 3])`` yields ``(1, 2, 3)`` and ``tuple('abc')``
1112yields ``('a', 'b', 'c')``. If the argument is a tuple, it does not make a copy
1113but returns the same object, so it is cheap to call :func:`tuple` when you
1114aren't sure that an object is already a tuple.
1115
1116The type constructor ``list(seq)`` converts any sequence or iterable into a list
1117with the same items in the same order. For example, ``list((1, 2, 3))`` yields
1118``[1, 2, 3]`` and ``list('abc')`` yields ``['a', 'b', 'c']``. If the argument
1119is a list, it makes a copy just like ``seq[:]`` would.
1120
1121
1122What's a negative index?
1123------------------------
1124
1125Python sequences are indexed with positive numbers and negative numbers. For
1126positive numbers 0 is the first index 1 is the second index and so forth. For
1127negative indices -1 is the last index and -2 is the penultimate (next to last)
1128index and so forth. Think of ``seq[-n]`` as the same as ``seq[len(seq)-n]``.
1129
1130Using negative indices can be very convenient. For example ``S[:-1]`` is all of
1131the string except for its last character, which is useful for removing the
1132trailing newline from a string.
1133
1134
1135How do I iterate over a sequence in reverse order?
1136--------------------------------------------------
1137
Georg Brandlc4a55fc2010-02-06 18:46:57 +00001138Use the :func:`reversed` built-in function, which is new in Python 2.4::
Georg Brandld7413152009-10-11 21:25:26 +00001139
1140 for x in reversed(sequence):
Serhiy Storchakadba90392016-05-10 12:01:23 +03001141 ... # do something with x ...
Georg Brandld7413152009-10-11 21:25:26 +00001142
1143This won't touch your original sequence, but build a new copy with reversed
1144order to iterate over.
1145
1146With Python 2.3, you can use an extended slice syntax::
1147
1148 for x in sequence[::-1]:
Serhiy Storchakadba90392016-05-10 12:01:23 +03001149 ... # do something with x ...
Georg Brandld7413152009-10-11 21:25:26 +00001150
1151
1152How do you remove duplicates from a list?
1153-----------------------------------------
1154
1155See the Python Cookbook for a long discussion of many ways to do this:
1156
Serhiy Storchaka6dff0202016-05-07 10:49:07 +03001157 https://code.activestate.com/recipes/52560/
Georg Brandld7413152009-10-11 21:25:26 +00001158
1159If you don't mind reordering the list, sort it and then scan from the end of the
1160list, deleting duplicates as you go::
1161
Georg Brandl62eaaf62009-12-19 17:51:41 +00001162 if mylist:
1163 mylist.sort()
1164 last = mylist[-1]
1165 for i in range(len(mylist)-2, -1, -1):
1166 if last == mylist[i]:
1167 del mylist[i]
Georg Brandld7413152009-10-11 21:25:26 +00001168 else:
Georg Brandl62eaaf62009-12-19 17:51:41 +00001169 last = mylist[i]
Georg Brandld7413152009-10-11 21:25:26 +00001170
Antoine Pitrouf3520402011-12-03 22:19:55 +01001171If all elements of the list may be used as set keys (i.e. they are all
1172:term:`hashable`) this is often faster ::
Georg Brandld7413152009-10-11 21:25:26 +00001173
Georg Brandl62eaaf62009-12-19 17:51:41 +00001174 mylist = list(set(mylist))
Georg Brandld7413152009-10-11 21:25:26 +00001175
1176This converts the list into a set, thereby removing duplicates, and then back
1177into a list.
1178
1179
1180How do you make an array in Python?
1181-----------------------------------
1182
1183Use a list::
1184
1185 ["this", 1, "is", "an", "array"]
1186
1187Lists are equivalent to C or Pascal arrays in their time complexity; the primary
1188difference is that a Python list can contain objects of many different types.
1189
1190The ``array`` module also provides methods for creating arrays of fixed types
1191with compact representations, but they are slower to index than lists. Also
1192note that the Numeric extensions and others define array-like structures with
1193various characteristics as well.
1194
1195To get Lisp-style linked lists, you can emulate cons cells using tuples::
1196
1197 lisp_list = ("like", ("this", ("example", None) ) )
1198
1199If mutability is desired, you could use lists instead of tuples. Here the
1200analogue of lisp car is ``lisp_list[0]`` and the analogue of cdr is
1201``lisp_list[1]``. Only do this if you're sure you really need to, because it's
1202usually a lot slower than using Python lists.
1203
1204
Martin Panter7f02d6d2015-09-07 02:08:55 +00001205.. _faq-multidimensional-list:
1206
Georg Brandld7413152009-10-11 21:25:26 +00001207How do I create a multidimensional list?
1208----------------------------------------
1209
1210You probably tried to make a multidimensional array like this::
1211
R David Murrayfdf95032013-06-19 16:58:26 -04001212 >>> A = [[None] * 2] * 3
Georg Brandld7413152009-10-11 21:25:26 +00001213
Senthil Kumaran77493202016-06-04 20:07:34 -07001214This looks correct if you print it:
1215
1216.. testsetup::
1217
1218 A = [[None] * 2] * 3
1219
1220.. doctest::
Georg Brandld7413152009-10-11 21:25:26 +00001221
1222 >>> A
1223 [[None, None], [None, None], [None, None]]
1224
1225But when you assign a value, it shows up in multiple places:
1226
Senthil Kumaran77493202016-06-04 20:07:34 -07001227.. testsetup::
1228
1229 A = [[None] * 2] * 3
1230
1231.. doctest::
1232
1233 >>> A[0][0] = 5
1234 >>> A
1235 [[5, None], [5, None], [5, None]]
Georg Brandld7413152009-10-11 21:25:26 +00001236
1237The reason is that replicating a list with ``*`` doesn't create copies, it only
1238creates references to the existing objects. The ``*3`` creates a list
1239containing 3 references to the same list of length two. Changes to one row will
1240show in all rows, which is almost certainly not what you want.
1241
1242The suggested approach is to create a list of the desired length first and then
1243fill in each element with a newly created list::
1244
1245 A = [None] * 3
1246 for i in range(3):
1247 A[i] = [None] * 2
1248
1249This generates a list containing 3 different lists of length two. You can also
1250use a list comprehension::
1251
1252 w, h = 2, 3
1253 A = [[None] * w for i in range(h)]
1254
Benjamin Peterson6d3ad2f2016-05-26 22:51:32 -07001255Or, you can use an extension that provides a matrix datatype; `NumPy
Ezio Melottic1f58392013-06-09 01:04:21 +03001256<http://www.numpy.org/>`_ is the best known.
Georg Brandld7413152009-10-11 21:25:26 +00001257
1258
1259How do I apply a method to a sequence of objects?
1260-------------------------------------------------
1261
1262Use a list comprehension::
1263
Georg Brandl62eaaf62009-12-19 17:51:41 +00001264 result = [obj.method() for obj in mylist]
Georg Brandld7413152009-10-11 21:25:26 +00001265
Larry Hastings3732ed22014-03-15 21:13:56 -07001266.. _faq-augmented-assignment-tuple-error:
Georg Brandld7413152009-10-11 21:25:26 +00001267
R David Murraybcf06d32013-05-20 10:32:46 -04001268Why does a_tuple[i] += ['item'] raise an exception when the addition works?
1269---------------------------------------------------------------------------
1270
1271This is because of a combination of the fact that augmented assignment
1272operators are *assignment* operators, and the difference between mutable and
1273immutable objects in Python.
1274
1275This discussion applies in general when augmented assignment operators are
1276applied to elements of a tuple that point to mutable objects, but we'll use
1277a ``list`` and ``+=`` as our exemplar.
1278
1279If you wrote::
1280
1281 >>> a_tuple = (1, 2)
1282 >>> a_tuple[0] += 1
1283 Traceback (most recent call last):
1284 ...
1285 TypeError: 'tuple' object does not support item assignment
1286
1287The reason for the exception should be immediately clear: ``1`` is added to the
1288object ``a_tuple[0]`` points to (``1``), producing the result object, ``2``,
1289but when we attempt to assign the result of the computation, ``2``, to element
1290``0`` of the tuple, we get an error because we can't change what an element of
1291a tuple points to.
1292
1293Under the covers, what this augmented assignment statement is doing is
1294approximately this::
1295
R David Murray95ae9922013-05-21 11:44:41 -04001296 >>> result = a_tuple[0] + 1
R David Murraybcf06d32013-05-20 10:32:46 -04001297 >>> a_tuple[0] = result
1298 Traceback (most recent call last):
1299 ...
1300 TypeError: 'tuple' object does not support item assignment
1301
1302It is the assignment part of the operation that produces the error, since a
1303tuple is immutable.
1304
1305When you write something like::
1306
1307 >>> a_tuple = (['foo'], 'bar')
1308 >>> a_tuple[0] += ['item']
1309 Traceback (most recent call last):
1310 ...
1311 TypeError: 'tuple' object does not support item assignment
1312
1313The exception is a bit more surprising, and even more surprising is the fact
1314that even though there was an error, the append worked::
1315
1316 >>> a_tuple[0]
1317 ['foo', 'item']
1318
R David Murray95ae9922013-05-21 11:44:41 -04001319To see why this happens, you need to know that (a) if an object implements an
1320``__iadd__`` magic method, it gets called when the ``+=`` augmented assignment
1321is executed, and its return value is what gets used in the assignment statement;
1322and (b) for lists, ``__iadd__`` is equivalent to calling ``extend`` on the list
1323and returning the list. That's why we say that for lists, ``+=`` is a
1324"shorthand" for ``list.extend``::
R David Murraybcf06d32013-05-20 10:32:46 -04001325
1326 >>> a_list = []
1327 >>> a_list += [1]
1328 >>> a_list
1329 [1]
1330
R David Murray95ae9922013-05-21 11:44:41 -04001331This is equivalent to::
R David Murraybcf06d32013-05-20 10:32:46 -04001332
1333 >>> result = a_list.__iadd__([1])
1334 >>> a_list = result
1335
1336The object pointed to by a_list has been mutated, and the pointer to the
1337mutated object is assigned back to ``a_list``. The end result of the
1338assignment is a no-op, since it is a pointer to the same object that ``a_list``
1339was previously pointing to, but the assignment still happens.
1340
1341Thus, in our tuple example what is happening is equivalent to::
1342
1343 >>> result = a_tuple[0].__iadd__(['item'])
1344 >>> a_tuple[0] = result
1345 Traceback (most recent call last):
1346 ...
1347 TypeError: 'tuple' object does not support item assignment
1348
1349The ``__iadd__`` succeeds, and thus the list is extended, but even though
1350``result`` points to the same object that ``a_tuple[0]`` already points to,
1351that final assignment still results in an error, because tuples are immutable.
1352
1353
Georg Brandld7413152009-10-11 21:25:26 +00001354I want to do a complicated sort: can you do a Schwartzian Transform in Python?
1355------------------------------------------------------------------------------
1356
1357The technique, attributed to Randal Schwartz of the Perl community, sorts the
1358elements of a list by a metric which maps each element to its "sort value". In
Berker Peksag5b6a14d2016-06-01 13:54:33 -07001359Python, use the ``key`` argument for the :meth:`list.sort` method::
Georg Brandld7413152009-10-11 21:25:26 +00001360
1361 Isorted = L[:]
1362 Isorted.sort(key=lambda s: int(s[10:15]))
1363
Georg Brandld7413152009-10-11 21:25:26 +00001364
1365How can I sort one list by values from another list?
1366----------------------------------------------------
1367
Georg Brandl62eaaf62009-12-19 17:51:41 +00001368Merge them into an iterator of tuples, sort the resulting list, and then pick
Georg Brandld7413152009-10-11 21:25:26 +00001369out the element you want. ::
1370
1371 >>> list1 = ["what", "I'm", "sorting", "by"]
1372 >>> list2 = ["something", "else", "to", "sort"]
1373 >>> pairs = zip(list1, list2)
Georg Brandl62eaaf62009-12-19 17:51:41 +00001374 >>> pairs = sorted(pairs)
Georg Brandld7413152009-10-11 21:25:26 +00001375 >>> pairs
Georg Brandl62eaaf62009-12-19 17:51:41 +00001376 [("I'm", 'else'), ('by', 'sort'), ('sorting', 'to'), ('what', 'something')]
1377 >>> result = [x[1] for x in pairs]
Georg Brandld7413152009-10-11 21:25:26 +00001378 >>> result
1379 ['else', 'sort', 'to', 'something']
1380
Georg Brandl62eaaf62009-12-19 17:51:41 +00001381
Georg Brandld7413152009-10-11 21:25:26 +00001382An alternative for the last step is::
1383
Georg Brandl62eaaf62009-12-19 17:51:41 +00001384 >>> result = []
1385 >>> for p in pairs: result.append(p[1])
Georg Brandld7413152009-10-11 21:25:26 +00001386
1387If you find this more legible, you might prefer to use this instead of the final
1388list comprehension. However, it is almost twice as slow for long lists. Why?
1389First, the ``append()`` operation has to reallocate memory, and while it uses
1390some tricks to avoid doing that each time, it still has to do it occasionally,
1391and that costs quite a bit. Second, the expression "result.append" requires an
1392extra attribute lookup, and third, there's a speed reduction from having to make
1393all those function calls.
1394
1395
1396Objects
1397=======
1398
1399What is a class?
1400----------------
1401
1402A class is the particular object type created by executing a class statement.
1403Class objects are used as templates to create instance objects, which embody
1404both the data (attributes) and code (methods) specific to a datatype.
1405
1406A class can be based on one or more other classes, called its base class(es). It
1407then inherits the attributes and methods of its base classes. This allows an
1408object model to be successively refined by inheritance. You might have a
1409generic ``Mailbox`` class that provides basic accessor methods for a mailbox,
1410and subclasses such as ``MboxMailbox``, ``MaildirMailbox``, ``OutlookMailbox``
1411that handle various specific mailbox formats.
1412
1413
1414What is a method?
1415-----------------
1416
1417A method is a function on some object ``x`` that you normally call as
1418``x.name(arguments...)``. Methods are defined as functions inside the class
1419definition::
1420
1421 class C:
Serhiy Storchakadba90392016-05-10 12:01:23 +03001422 def meth(self, arg):
Georg Brandld7413152009-10-11 21:25:26 +00001423 return arg * 2 + self.attribute
1424
1425
1426What is self?
1427-------------
1428
1429Self is merely a conventional name for the first argument of a method. A method
1430defined as ``meth(self, a, b, c)`` should be called as ``x.meth(a, b, c)`` for
1431some instance ``x`` of the class in which the definition occurs; the called
1432method will think it is called as ``meth(x, a, b, c)``.
1433
1434See also :ref:`why-self`.
1435
1436
1437How do I check if an object is an instance of a given class or of a subclass of it?
1438-----------------------------------------------------------------------------------
1439
1440Use the built-in function ``isinstance(obj, cls)``. You can check if an object
1441is an instance of any of a number of classes by providing a tuple instead of a
1442single class, e.g. ``isinstance(obj, (class1, class2, ...))``, and can also
1443check whether an object is one of Python's built-in types, e.g.
Georg Brandl62eaaf62009-12-19 17:51:41 +00001444``isinstance(obj, str)`` or ``isinstance(obj, (int, float, complex))``.
Georg Brandld7413152009-10-11 21:25:26 +00001445
1446Note that most programs do not use :func:`isinstance` on user-defined classes
1447very often. If you are developing the classes yourself, a more proper
1448object-oriented style is to define methods on the classes that encapsulate a
1449particular behaviour, instead of checking the object's class and doing a
1450different thing based on what class it is. For example, if you have a function
1451that does something::
1452
Georg Brandl62eaaf62009-12-19 17:51:41 +00001453 def search(obj):
Georg Brandld7413152009-10-11 21:25:26 +00001454 if isinstance(obj, Mailbox):
Serhiy Storchakadba90392016-05-10 12:01:23 +03001455 ... # code to search a mailbox
Georg Brandld7413152009-10-11 21:25:26 +00001456 elif isinstance(obj, Document):
Serhiy Storchakadba90392016-05-10 12:01:23 +03001457 ... # code to search a document
Georg Brandld7413152009-10-11 21:25:26 +00001458 elif ...
1459
1460A better approach is to define a ``search()`` method on all the classes and just
1461call it::
1462
1463 class Mailbox:
1464 def search(self):
Serhiy Storchakadba90392016-05-10 12:01:23 +03001465 ... # code to search a mailbox
Georg Brandld7413152009-10-11 21:25:26 +00001466
1467 class Document:
1468 def search(self):
Serhiy Storchakadba90392016-05-10 12:01:23 +03001469 ... # code to search a document
Georg Brandld7413152009-10-11 21:25:26 +00001470
1471 obj.search()
1472
1473
1474What is delegation?
1475-------------------
1476
1477Delegation is an object oriented technique (also called a design pattern).
1478Let's say you have an object ``x`` and want to change the behaviour of just one
1479of its methods. You can create a new class that provides a new implementation
1480of the method you're interested in changing and delegates all other methods to
1481the corresponding method of ``x``.
1482
1483Python programmers can easily implement delegation. For example, the following
1484class implements a class that behaves like a file but converts all written data
1485to uppercase::
1486
1487 class UpperOut:
1488
1489 def __init__(self, outfile):
1490 self._outfile = outfile
1491
1492 def write(self, s):
1493 self._outfile.write(s.upper())
1494
1495 def __getattr__(self, name):
1496 return getattr(self._outfile, name)
1497
1498Here the ``UpperOut`` class redefines the ``write()`` method to convert the
1499argument string to uppercase before calling the underlying
1500``self.__outfile.write()`` method. All other methods are delegated to the
1501underlying ``self.__outfile`` object. The delegation is accomplished via the
1502``__getattr__`` method; consult :ref:`the language reference <attribute-access>`
1503for more information about controlling attribute access.
1504
1505Note that for more general cases delegation can get trickier. When attributes
1506must be set as well as retrieved, the class must define a :meth:`__setattr__`
1507method too, and it must do so carefully. The basic implementation of
1508:meth:`__setattr__` is roughly equivalent to the following::
1509
1510 class X:
1511 ...
1512 def __setattr__(self, name, value):
1513 self.__dict__[name] = value
1514 ...
1515
1516Most :meth:`__setattr__` implementations must modify ``self.__dict__`` to store
1517local state for self without causing an infinite recursion.
1518
1519
1520How do I call a method defined in a base class from a derived class that overrides it?
1521--------------------------------------------------------------------------------------
1522
Georg Brandl62eaaf62009-12-19 17:51:41 +00001523Use the built-in :func:`super` function::
Georg Brandld7413152009-10-11 21:25:26 +00001524
1525 class Derived(Base):
Serhiy Storchakadba90392016-05-10 12:01:23 +03001526 def meth(self):
Georg Brandld7413152009-10-11 21:25:26 +00001527 super(Derived, self).meth()
1528
Georg Brandl62eaaf62009-12-19 17:51:41 +00001529For version prior to 3.0, you may be using classic classes: For a class
1530definition such as ``class Derived(Base): ...`` you can call method ``meth()``
1531defined in ``Base`` (or one of ``Base``'s base classes) as ``Base.meth(self,
1532arguments...)``. Here, ``Base.meth`` is an unbound method, so you need to
1533provide the ``self`` argument.
Georg Brandld7413152009-10-11 21:25:26 +00001534
1535
1536How can I organize my code to make it easier to change the base class?
1537----------------------------------------------------------------------
1538
1539You could define an alias for the base class, assign the real base class to it
1540before your class definition, and use the alias throughout your class. Then all
1541you have to change is the value assigned to the alias. Incidentally, this trick
1542is also handy if you want to decide dynamically (e.g. depending on availability
1543of resources) which base class to use. Example::
1544
1545 BaseAlias = <real base class>
1546
1547 class Derived(BaseAlias):
1548 def meth(self):
1549 BaseAlias.meth(self)
1550 ...
1551
1552
1553How do I create static class data and static class methods?
1554-----------------------------------------------------------
1555
Georg Brandl62eaaf62009-12-19 17:51:41 +00001556Both static data and static methods (in the sense of C++ or Java) are supported
1557in Python.
Georg Brandld7413152009-10-11 21:25:26 +00001558
1559For static data, simply define a class attribute. To assign a new value to the
1560attribute, you have to explicitly use the class name in the assignment::
1561
1562 class C:
1563 count = 0 # number of times C.__init__ called
1564
1565 def __init__(self):
1566 C.count = C.count + 1
1567
1568 def getcount(self):
1569 return C.count # or return self.count
1570
1571``c.count`` also refers to ``C.count`` for any ``c`` such that ``isinstance(c,
1572C)`` holds, unless overridden by ``c`` itself or by some class on the base-class
1573search path from ``c.__class__`` back to ``C``.
1574
1575Caution: within a method of C, an assignment like ``self.count = 42`` creates a
Georg Brandl62eaaf62009-12-19 17:51:41 +00001576new and unrelated instance named "count" in ``self``'s own dict. Rebinding of a
1577class-static data name must always specify the class whether inside a method or
1578not::
Georg Brandld7413152009-10-11 21:25:26 +00001579
1580 C.count = 314
1581
Antoine Pitrouf3520402011-12-03 22:19:55 +01001582Static methods are possible::
Georg Brandld7413152009-10-11 21:25:26 +00001583
1584 class C:
1585 @staticmethod
1586 def static(arg1, arg2, arg3):
1587 # No 'self' parameter!
1588 ...
1589
1590However, a far more straightforward way to get the effect of a static method is
1591via a simple module-level function::
1592
1593 def getcount():
1594 return C.count
1595
1596If your code is structured so as to define one class (or tightly related class
1597hierarchy) per module, this supplies the desired encapsulation.
1598
1599
1600How can I overload constructors (or methods) in Python?
1601-------------------------------------------------------
1602
1603This answer actually applies to all methods, but the question usually comes up
1604first in the context of constructors.
1605
1606In C++ you'd write
1607
1608.. code-block:: c
1609
1610 class C {
1611 C() { cout << "No arguments\n"; }
1612 C(int i) { cout << "Argument is " << i << "\n"; }
1613 }
1614
1615In Python you have to write a single constructor that catches all cases using
1616default arguments. For example::
1617
1618 class C:
1619 def __init__(self, i=None):
1620 if i is None:
Georg Brandl62eaaf62009-12-19 17:51:41 +00001621 print("No arguments")
Georg Brandld7413152009-10-11 21:25:26 +00001622 else:
Georg Brandl62eaaf62009-12-19 17:51:41 +00001623 print("Argument is", i)
Georg Brandld7413152009-10-11 21:25:26 +00001624
1625This is not entirely equivalent, but close enough in practice.
1626
1627You could also try a variable-length argument list, e.g. ::
1628
1629 def __init__(self, *args):
1630 ...
1631
1632The same approach works for all method definitions.
1633
1634
1635I try to use __spam and I get an error about _SomeClassName__spam.
1636------------------------------------------------------------------
1637
1638Variable names with double leading underscores are "mangled" to provide a simple
1639but effective way to define class private variables. Any identifier of the form
1640``__spam`` (at least two leading underscores, at most one trailing underscore)
1641is textually replaced with ``_classname__spam``, where ``classname`` is the
1642current class name with any leading underscores stripped.
1643
1644This doesn't guarantee privacy: an outside user can still deliberately access
1645the "_classname__spam" attribute, and private values are visible in the object's
1646``__dict__``. Many Python programmers never bother to use private variable
1647names at all.
1648
1649
1650My class defines __del__ but it is not called when I delete the object.
1651-----------------------------------------------------------------------
1652
1653There are several possible reasons for this.
1654
1655The del statement does not necessarily call :meth:`__del__` -- it simply
1656decrements the object's reference count, and if this reaches zero
1657:meth:`__del__` is called.
1658
1659If your data structures contain circular links (e.g. a tree where each child has
1660a parent reference and each parent has a list of children) the reference counts
1661will never go back to zero. Once in a while Python runs an algorithm to detect
1662such cycles, but the garbage collector might run some time after the last
1663reference to your data structure vanishes, so your :meth:`__del__` method may be
1664called at an inconvenient and random time. This is inconvenient if you're trying
1665to reproduce a problem. Worse, the order in which object's :meth:`__del__`
1666methods are executed is arbitrary. You can run :func:`gc.collect` to force a
1667collection, but there *are* pathological cases where objects will never be
1668collected.
1669
1670Despite the cycle collector, it's still a good idea to define an explicit
1671``close()`` method on objects to be called whenever you're done with them. The
Gregory P. Smithe9d978f2017-08-28 13:43:26 -07001672``close()`` method can then remove attributes that refer to subobjects. Don't
Georg Brandld7413152009-10-11 21:25:26 +00001673call :meth:`__del__` directly -- :meth:`__del__` should call ``close()`` and
1674``close()`` should make sure that it can be called more than once for the same
1675object.
1676
1677Another way to avoid cyclical references is to use the :mod:`weakref` module,
1678which allows you to point to objects without incrementing their reference count.
1679Tree data structures, for instance, should use weak references for their parent
1680and sibling references (if they need them!).
1681
Georg Brandl62eaaf62009-12-19 17:51:41 +00001682.. XXX relevant for Python 3?
1683
1684 If the object has ever been a local variable in a function that caught an
1685 expression in an except clause, chances are that a reference to the object
1686 still exists in that function's stack frame as contained in the stack trace.
1687 Normally, calling :func:`sys.exc_clear` will take care of this by clearing
1688 the last recorded exception.
Georg Brandld7413152009-10-11 21:25:26 +00001689
1690Finally, if your :meth:`__del__` method raises an exception, a warning message
1691is printed to :data:`sys.stderr`.
1692
1693
1694How do I get a list of all instances of a given class?
1695------------------------------------------------------
1696
1697Python does not keep track of all instances of a class (or of a built-in type).
1698You can program the class's constructor to keep track of all instances by
1699keeping a list of weak references to each instance.
1700
1701
Georg Brandld8ede4f2013-10-12 18:14:25 +02001702Why does the result of ``id()`` appear to be not unique?
1703--------------------------------------------------------
1704
1705The :func:`id` builtin returns an integer that is guaranteed to be unique during
1706the lifetime of the object. Since in CPython, this is the object's memory
1707address, it happens frequently that after an object is deleted from memory, the
1708next freshly created object is allocated at the same position in memory. This
1709is illustrated by this example:
1710
Senthil Kumaran77493202016-06-04 20:07:34 -07001711>>> id(1000) # doctest: +SKIP
Georg Brandld8ede4f2013-10-12 18:14:25 +0200171213901272
Senthil Kumaran77493202016-06-04 20:07:34 -07001713>>> id(2000) # doctest: +SKIP
Georg Brandld8ede4f2013-10-12 18:14:25 +0200171413901272
1715
1716The two ids belong to different integer objects that are created before, and
1717deleted immediately after execution of the ``id()`` call. To be sure that
1718objects whose id you want to examine are still alive, create another reference
1719to the object:
1720
1721>>> a = 1000; b = 2000
Senthil Kumaran77493202016-06-04 20:07:34 -07001722>>> id(a) # doctest: +SKIP
Georg Brandld8ede4f2013-10-12 18:14:25 +0200172313901272
Senthil Kumaran77493202016-06-04 20:07:34 -07001724>>> id(b) # doctest: +SKIP
Georg Brandld8ede4f2013-10-12 18:14:25 +0200172513891296
1726
1727
Georg Brandld7413152009-10-11 21:25:26 +00001728Modules
1729=======
1730
1731How do I create a .pyc file?
1732----------------------------
1733
R David Murrayd913d9d2013-12-13 12:29:29 -05001734When a module is imported for the first time (or when the source file has
1735changed since the current compiled file was created) a ``.pyc`` file containing
1736the compiled code should be created in a ``__pycache__`` subdirectory of the
1737directory containing the ``.py`` file. The ``.pyc`` file will have a
1738filename that starts with the same name as the ``.py`` file, and ends with
1739``.pyc``, with a middle component that depends on the particular ``python``
1740binary that created it. (See :pep:`3147` for details.)
Georg Brandld7413152009-10-11 21:25:26 +00001741
R David Murrayd913d9d2013-12-13 12:29:29 -05001742One reason that a ``.pyc`` file may not be created is a permissions problem
1743with the directory containing the source file, meaning that the ``__pycache__``
1744subdirectory cannot be created. This can happen, for example, if you develop as
1745one user but run as another, such as if you are testing with a web server.
1746
1747Unless the :envvar:`PYTHONDONTWRITEBYTECODE` environment variable is set,
1748creation of a .pyc file is automatic if you're importing a module and Python
1749has the ability (permissions, free space, etc...) to create a ``__pycache__``
1750subdirectory and write the compiled module to that subdirectory.
Georg Brandld7413152009-10-11 21:25:26 +00001751
R David Murrayfdf95032013-06-19 16:58:26 -04001752Running Python on a top level script is not considered an import and no
1753``.pyc`` will be created. For example, if you have a top-level module
R David Murrayd913d9d2013-12-13 12:29:29 -05001754``foo.py`` that imports another module ``xyz.py``, when you run ``foo`` (by
1755typing ``python foo.py`` as a shell command), a ``.pyc`` will be created for
1756``xyz`` because ``xyz`` is imported, but no ``.pyc`` file will be created for
1757``foo`` since ``foo.py`` isn't being imported.
Georg Brandld7413152009-10-11 21:25:26 +00001758
R David Murrayd913d9d2013-12-13 12:29:29 -05001759If you need to create a ``.pyc`` file for ``foo`` -- that is, to create a
1760``.pyc`` file for a module that is not imported -- you can, using the
1761:mod:`py_compile` and :mod:`compileall` modules.
Georg Brandld7413152009-10-11 21:25:26 +00001762
1763The :mod:`py_compile` module can manually compile any module. One way is to use
1764the ``compile()`` function in that module interactively::
1765
1766 >>> import py_compile
R David Murrayfdf95032013-06-19 16:58:26 -04001767 >>> py_compile.compile('foo.py') # doctest: +SKIP
Georg Brandld7413152009-10-11 21:25:26 +00001768
R David Murrayd913d9d2013-12-13 12:29:29 -05001769This will write the ``.pyc`` to a ``__pycache__`` subdirectory in the same
1770location as ``foo.py`` (or you can override that with the optional parameter
1771``cfile``).
Georg Brandld7413152009-10-11 21:25:26 +00001772
1773You can also automatically compile all files in a directory or directories using
1774the :mod:`compileall` module. You can do it from the shell prompt by running
1775``compileall.py`` and providing the path of a directory containing Python files
1776to compile::
1777
1778 python -m compileall .
1779
1780
1781How do I find the current module name?
1782--------------------------------------
1783
1784A module can find out its own module name by looking at the predefined global
1785variable ``__name__``. If this has the value ``'__main__'``, the program is
1786running as a script. Many modules that are usually used by importing them also
1787provide a command-line interface or a self-test, and only execute this code
1788after checking ``__name__``::
1789
1790 def main():
Georg Brandl62eaaf62009-12-19 17:51:41 +00001791 print('Running test...')
Georg Brandld7413152009-10-11 21:25:26 +00001792 ...
1793
1794 if __name__ == '__main__':
1795 main()
1796
1797
1798How can I have modules that mutually import each other?
1799-------------------------------------------------------
1800
1801Suppose you have the following modules:
1802
1803foo.py::
1804
1805 from bar import bar_var
1806 foo_var = 1
1807
1808bar.py::
1809
1810 from foo import foo_var
1811 bar_var = 2
1812
1813The problem is that the interpreter will perform the following steps:
1814
1815* main imports foo
1816* Empty globals for foo are created
1817* foo is compiled and starts executing
1818* foo imports bar
1819* Empty globals for bar are created
1820* bar is compiled and starts executing
1821* bar imports foo (which is a no-op since there already is a module named foo)
1822* bar.foo_var = foo.foo_var
1823
1824The last step fails, because Python isn't done with interpreting ``foo`` yet and
1825the global symbol dictionary for ``foo`` is still empty.
1826
1827The same thing happens when you use ``import foo``, and then try to access
1828``foo.foo_var`` in global code.
1829
1830There are (at least) three possible workarounds for this problem.
1831
1832Guido van Rossum recommends avoiding all uses of ``from <module> import ...``,
1833and placing all code inside functions. Initializations of global variables and
1834class variables should use constants or built-in functions only. This means
1835everything from an imported module is referenced as ``<module>.<name>``.
1836
1837Jim Roskind suggests performing steps in the following order in each module:
1838
1839* exports (globals, functions, and classes that don't need imported base
1840 classes)
1841* ``import`` statements
1842* active code (including globals that are initialized from imported values).
1843
1844van Rossum doesn't like this approach much because the imports appear in a
1845strange place, but it does work.
1846
1847Matthias Urlichs recommends restructuring your code so that the recursive import
1848is not necessary in the first place.
1849
1850These solutions are not mutually exclusive.
1851
1852
1853__import__('x.y.z') returns <module 'x'>; how do I get z?
1854---------------------------------------------------------
1855
Ezio Melottie4aad5a2014-08-04 19:34:29 +03001856Consider using the convenience function :func:`~importlib.import_module` from
1857:mod:`importlib` instead::
Georg Brandld7413152009-10-11 21:25:26 +00001858
Ezio Melottie4aad5a2014-08-04 19:34:29 +03001859 z = importlib.import_module('x.y.z')
Georg Brandld7413152009-10-11 21:25:26 +00001860
1861
1862When I edit an imported module and reimport it, the changes don't show up. Why does this happen?
1863-------------------------------------------------------------------------------------------------
1864
1865For reasons of efficiency as well as consistency, Python only reads the module
1866file on the first time a module is imported. If it didn't, in a program
1867consisting of many modules where each one imports the same basic module, the
Brett Cannon4f422e32013-06-14 22:49:00 -04001868basic module would be parsed and re-parsed many times. To force re-reading of a
Georg Brandld7413152009-10-11 21:25:26 +00001869changed module, do this::
1870
Brett Cannon4f422e32013-06-14 22:49:00 -04001871 import importlib
Georg Brandld7413152009-10-11 21:25:26 +00001872 import modname
Brett Cannon4f422e32013-06-14 22:49:00 -04001873 importlib.reload(modname)
Georg Brandld7413152009-10-11 21:25:26 +00001874
1875Warning: this technique is not 100% fool-proof. In particular, modules
1876containing statements like ::
1877
1878 from modname import some_objects
1879
1880will continue to work with the old version of the imported objects. If the
1881module contains class definitions, existing class instances will *not* be
1882updated to use the new class definition. This can result in the following
Marco Buttu909a6f62017-03-18 17:59:33 +01001883paradoxical behaviour::
Georg Brandld7413152009-10-11 21:25:26 +00001884
Brett Cannon4f422e32013-06-14 22:49:00 -04001885 >>> import importlib
Georg Brandld7413152009-10-11 21:25:26 +00001886 >>> import cls
1887 >>> c = cls.C() # Create an instance of C
Brett Cannon4f422e32013-06-14 22:49:00 -04001888 >>> importlib.reload(cls)
Georg Brandl62eaaf62009-12-19 17:51:41 +00001889 <module 'cls' from 'cls.py'>
Georg Brandld7413152009-10-11 21:25:26 +00001890 >>> isinstance(c, cls.C) # isinstance is false?!?
1891 False
1892
Georg Brandl62eaaf62009-12-19 17:51:41 +00001893The nature of the problem is made clear if you print out the "identity" of the
Marco Buttu909a6f62017-03-18 17:59:33 +01001894class objects::
Georg Brandld7413152009-10-11 21:25:26 +00001895
Georg Brandl62eaaf62009-12-19 17:51:41 +00001896 >>> hex(id(c.__class__))
1897 '0x7352a0'
1898 >>> hex(id(cls.C))
1899 '0x4198d0'