blob: 694753e5b9acf2b5ce6629201f9efe3bf4a019cd [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
74
75How can I create a stand-alone binary from a Python script?
76-----------------------------------------------------------
77
78You don't need the ability to compile Python to C code if all you want is a
79stand-alone program that users can download and run without having to install
80the Python distribution first. There are a number of tools that determine the
81set of modules required by a program and bind these modules together with a
82Python binary to produce a single executable.
83
84One is to use the freeze tool, which is included in the Python source tree as
85``Tools/freeze``. It converts Python byte code to C arrays; a C compiler you can
86embed all your modules into a new program, which is then linked with the
87standard Python modules.
88
89It works by scanning your source recursively for import statements (in both
90forms) and looking for the modules in the standard Python path as well as in the
91source directory (for built-in modules). It then turns the bytecode for modules
92written in Python into C code (array initializers that can be turned into code
93objects using the marshal module) and creates a custom-made config file that
94only contains those built-in modules which are actually used in the program. It
95then compiles the generated C code and links it with the rest of the Python
96interpreter to form a self-contained binary which acts exactly like your script.
97
98Obviously, freeze requires a C compiler. There are several other utilities
99which don't. One is Thomas Heller's py2exe (Windows only) at
100
101 http://www.py2exe.org/
102
Georg Brandl77fe77d2014-10-29 09:24:54 +0100103Another tool is Anthony Tuininga's `cx_Freeze <http://cx-freeze.sourceforge.net/>`_.
Georg Brandld7413152009-10-11 21:25:26 +0000104
105
106Are there coding standards or a style guide for Python programs?
107----------------------------------------------------------------
108
109Yes. The coding style required for standard library modules is documented as
110:pep:`8`.
111
112
Georg Brandld7413152009-10-11 21:25:26 +0000113Core Language
114=============
115
R. David Murrayc04a6942009-11-14 22:21:32 +0000116Why am I getting an UnboundLocalError when the variable has a value?
117--------------------------------------------------------------------
Georg Brandld7413152009-10-11 21:25:26 +0000118
R. David Murrayc04a6942009-11-14 22:21:32 +0000119It can be a surprise to get the UnboundLocalError in previously working
120code when it is modified by adding an assignment statement somewhere in
121the body of a function.
Georg Brandld7413152009-10-11 21:25:26 +0000122
R. David Murrayc04a6942009-11-14 22:21:32 +0000123This code:
Georg Brandld7413152009-10-11 21:25:26 +0000124
R. David Murrayc04a6942009-11-14 22:21:32 +0000125 >>> x = 10
126 >>> def bar():
127 ... print(x)
128 >>> bar()
129 10
Georg Brandld7413152009-10-11 21:25:26 +0000130
R. David Murrayc04a6942009-11-14 22:21:32 +0000131works, but this code:
Georg Brandld7413152009-10-11 21:25:26 +0000132
R. David Murrayc04a6942009-11-14 22:21:32 +0000133 >>> x = 10
134 >>> def foo():
135 ... print(x)
136 ... x += 1
Georg Brandld7413152009-10-11 21:25:26 +0000137
R. David Murrayc04a6942009-11-14 22:21:32 +0000138results in an UnboundLocalError:
Georg Brandld7413152009-10-11 21:25:26 +0000139
R. David Murrayc04a6942009-11-14 22:21:32 +0000140 >>> foo()
141 Traceback (most recent call last):
142 ...
143 UnboundLocalError: local variable 'x' referenced before assignment
144
145This is because when you make an assignment to a variable in a scope, that
146variable becomes local to that scope and shadows any similarly named variable
147in the outer scope. Since the last statement in foo assigns a new value to
148``x``, the compiler recognizes it as a local variable. Consequently when the
R. David Murray18163c32009-11-14 22:27:22 +0000149earlier ``print(x)`` attempts to print the uninitialized local variable and
R. David Murrayc04a6942009-11-14 22:21:32 +0000150an error results.
151
152In the example above you can access the outer scope variable by declaring it
153global:
154
155 >>> x = 10
156 >>> def foobar():
157 ... global x
158 ... print(x)
159 ... x += 1
160 >>> foobar()
161 10
162
163This explicit declaration is required in order to remind you that (unlike the
164superficially analogous situation with class and instance variables) you are
165actually modifying the value of the variable in the outer scope:
166
167 >>> print(x)
168 11
169
170You can do a similar thing in a nested scope using the :keyword:`nonlocal`
171keyword:
172
173 >>> def foo():
174 ... x = 10
175 ... def bar():
176 ... nonlocal x
177 ... print(x)
178 ... x += 1
179 ... bar()
180 ... print(x)
181 >>> foo()
182 10
183 11
Georg Brandld7413152009-10-11 21:25:26 +0000184
185
186What are the rules for local and global variables in Python?
187------------------------------------------------------------
188
189In Python, variables that are only referenced inside a function are implicitly
Robert Collinsbd4dd542015-07-30 06:14:32 +1200190global. If a variable is assigned a value anywhere within the function's body,
191it's assumed to be a local unless explicitly declared as global.
Georg Brandld7413152009-10-11 21:25:26 +0000192
193Though a bit surprising at first, a moment's consideration explains this. On
194one hand, requiring :keyword:`global` for assigned variables provides a bar
195against unintended side-effects. On the other hand, if ``global`` was required
196for all global references, you'd be using ``global`` all the time. You'd have
Georg Brandlc4a55fc2010-02-06 18:46:57 +0000197to declare as global every reference to a built-in function or to a component of
Georg Brandld7413152009-10-11 21:25:26 +0000198an imported module. This clutter would defeat the usefulness of the ``global``
199declaration for identifying side-effects.
200
201
Ezio Melotticad8b0f2013-01-05 00:50:46 +0200202Why do lambdas defined in a loop with different values all return the same result?
203----------------------------------------------------------------------------------
204
205Assume you use a for loop to define a few different lambdas (or even plain
206functions), e.g.::
207
R David Murrayfdf95032013-06-19 16:58:26 -0400208 >>> squares = []
209 >>> for x in range(5):
Serhiy Storchakadba90392016-05-10 12:01:23 +0300210 ... squares.append(lambda: x**2)
Ezio Melotticad8b0f2013-01-05 00:50:46 +0200211
212This gives you a list that contains 5 lambdas that calculate ``x**2``. You
213might expect that, when called, they would return, respectively, ``0``, ``1``,
214``4``, ``9``, and ``16``. However, when you actually try you will see that
215they all return ``16``::
216
217 >>> squares[2]()
218 16
219 >>> squares[4]()
220 16
221
222This happens because ``x`` is not local to the lambdas, but is defined in
223the outer scope, and it is accessed when the lambda is called --- not when it
224is defined. At the end of the loop, the value of ``x`` is ``4``, so all the
225functions now return ``4**2``, i.e. ``16``. You can also verify this by
226changing the value of ``x`` and see how the results of the lambdas change::
227
228 >>> x = 8
229 >>> squares[2]()
230 64
231
232In order to avoid this, you need to save the values in variables local to the
233lambdas, so that they don't rely on the value of the global ``x``::
234
R David Murrayfdf95032013-06-19 16:58:26 -0400235 >>> squares = []
236 >>> for x in range(5):
Serhiy Storchakadba90392016-05-10 12:01:23 +0300237 ... squares.append(lambda n=x: n**2)
Ezio Melotticad8b0f2013-01-05 00:50:46 +0200238
239Here, ``n=x`` creates a new variable ``n`` local to the lambda and computed
240when the lambda is defined so that it has the same value that ``x`` had at
241that point in the loop. This means that the value of ``n`` will be ``0``
242in the first lambda, ``1`` in the second, ``2`` in the third, and so on.
243Therefore each lambda will now return the correct result::
244
245 >>> squares[2]()
246 4
247 >>> squares[4]()
248 16
249
250Note that this behaviour is not peculiar to lambdas, but applies to regular
251functions too.
252
253
Georg Brandld7413152009-10-11 21:25:26 +0000254How do I share global variables across modules?
255------------------------------------------------
256
257The canonical way to share information across modules within a single program is
258to create a special module (often called config or cfg). Just import the config
259module in all modules of your application; the module then becomes available as
260a global name. Because there is only one instance of each module, any changes
261made to the module object get reflected everywhere. For example:
262
263config.py::
264
265 x = 0 # Default value of the 'x' configuration setting
266
267mod.py::
268
269 import config
270 config.x = 1
271
272main.py::
273
274 import config
275 import mod
Georg Brandl62eaaf62009-12-19 17:51:41 +0000276 print(config.x)
Georg Brandld7413152009-10-11 21:25:26 +0000277
278Note that using a module is also the basis for implementing the Singleton design
279pattern, for the same reason.
280
281
282What are the "best practices" for using import in a module?
283-----------------------------------------------------------
284
285In general, don't use ``from modulename import *``. Doing so clutters the
Georg Brandla94ad1e2014-10-06 16:02:09 +0200286importer's namespace, and makes it much harder for linters to detect undefined
287names.
Georg Brandld7413152009-10-11 21:25:26 +0000288
289Import modules at the top of a file. Doing so makes it clear what other modules
290your code requires and avoids questions of whether the module name is in scope.
291Using one import per line makes it easy to add and delete module imports, but
292using multiple imports per line uses less screen space.
293
294It's good practice if you import modules in the following order:
295
Georg Brandl62eaaf62009-12-19 17:51:41 +00002961. standard library modules -- e.g. ``sys``, ``os``, ``getopt``, ``re``
Georg Brandld7413152009-10-11 21:25:26 +00002972. third-party library modules (anything installed in Python's site-packages
298 directory) -- e.g. mx.DateTime, ZODB, PIL.Image, etc.
2993. locally-developed modules
300
Georg Brandld7413152009-10-11 21:25:26 +0000301It is sometimes necessary to move imports to a function or class to avoid
302problems with circular imports. Gordon McMillan says:
303
304 Circular imports are fine where both modules use the "import <module>" form
305 of import. They fail when the 2nd module wants to grab a name out of the
306 first ("from module import name") and the import is at the top level. That's
307 because names in the 1st are not yet available, because the first module is
308 busy importing the 2nd.
309
310In this case, if the second module is only used in one function, then the import
311can easily be moved into that function. By the time the import is called, the
312first module will have finished initializing, and the second module can do its
313import.
314
315It may also be necessary to move imports out of the top level of code if some of
316the modules are platform-specific. In that case, it may not even be possible to
317import all of the modules at the top of the file. In this case, importing the
318correct modules in the corresponding platform-specific code is a good option.
319
320Only move imports into a local scope, such as inside a function definition, if
321it's necessary to solve a problem such as avoiding a circular import or are
322trying to reduce the initialization time of a module. This technique is
323especially helpful if many of the imports are unnecessary depending on how the
324program executes. You may also want to move imports into a function if the
325modules are only ever used in that function. Note that loading a module the
326first time may be expensive because of the one time initialization of the
327module, but loading a module multiple times is virtually free, costing only a
328couple of dictionary lookups. Even if the module name has gone out of scope,
329the module is probably available in :data:`sys.modules`.
330
Georg Brandld7413152009-10-11 21:25:26 +0000331
Ezio Melotti898eb822014-07-06 20:53:27 +0300332Why are default values shared between objects?
333----------------------------------------------
334
335This type of bug commonly bites neophyte programmers. Consider this function::
336
337 def foo(mydict={}): # Danger: shared reference to one dict for all calls
338 ... compute something ...
339 mydict[key] = value
340 return mydict
341
342The first time you call this function, ``mydict`` contains a single item. The
343second time, ``mydict`` contains two items because when ``foo()`` begins
344executing, ``mydict`` starts out with an item already in it.
345
346It is often expected that a function call creates new objects for default
347values. This is not what happens. Default values are created exactly once, when
348the function is defined. If that object is changed, like the dictionary in this
349example, subsequent calls to the function will refer to this changed object.
350
351By definition, immutable objects such as numbers, strings, tuples, and ``None``,
352are safe from change. Changes to mutable objects such as dictionaries, lists,
353and class instances can lead to confusion.
354
355Because of this feature, it is good programming practice to not use mutable
356objects as default values. Instead, use ``None`` as the default value and
357inside the function, check if the parameter is ``None`` and create a new
358list/dictionary/whatever if it is. For example, don't write::
359
360 def foo(mydict={}):
361 ...
362
363but::
364
365 def foo(mydict=None):
366 if mydict is None:
367 mydict = {} # create a new dict for local namespace
368
369This feature can be useful. When you have a function that's time-consuming to
370compute, a common technique is to cache the parameters and the resulting value
371of each call to the function, and return the cached value if the same value is
372requested again. This is called "memoizing", and can be implemented like this::
373
374 # Callers will never provide a third parameter for this function.
375 def expensive(arg1, arg2, _cache={}):
376 if (arg1, arg2) in _cache:
377 return _cache[(arg1, arg2)]
378
379 # Calculate the value
380 result = ... expensive computation ...
R David Murray623ae292014-09-28 11:01:11 -0400381 _cache[(arg1, arg2)] = result # Store result in the cache
Ezio Melotti898eb822014-07-06 20:53:27 +0300382 return result
383
384You could use a global variable containing a dictionary instead of the default
385value; it's a matter of taste.
386
387
Georg Brandld7413152009-10-11 21:25:26 +0000388How can I pass optional or keyword parameters from one function to another?
389---------------------------------------------------------------------------
390
391Collect the arguments using the ``*`` and ``**`` specifiers in the function's
392parameter list; this gives you the positional arguments as a tuple and the
393keyword arguments as a dictionary. You can then pass these arguments when
394calling another function by using ``*`` and ``**``::
395
396 def f(x, *args, **kwargs):
397 ...
398 kwargs['width'] = '14.3c'
399 ...
400 g(x, *args, **kwargs)
401
Georg Brandld7413152009-10-11 21:25:26 +0000402
Chris Jerdonekb4309942012-12-25 14:54:44 -0800403.. index::
404 single: argument; difference from parameter
405 single: parameter; difference from argument
406
Chris Jerdonekc2a7fd62012-11-28 02:29:33 -0800407.. _faq-argument-vs-parameter:
408
409What is the difference between arguments and parameters?
410--------------------------------------------------------
411
412:term:`Parameters <parameter>` are defined by the names that appear in a
413function definition, whereas :term:`arguments <argument>` are the values
414actually passed to a function when calling it. Parameters define what types of
415arguments a function can accept. For example, given the function definition::
416
417 def func(foo, bar=None, **kwargs):
418 pass
419
420*foo*, *bar* and *kwargs* are parameters of ``func``. However, when calling
421``func``, for example::
422
423 func(42, bar=314, extra=somevar)
424
425the values ``42``, ``314``, and ``somevar`` are arguments.
426
427
R David Murray623ae292014-09-28 11:01:11 -0400428Why did changing list 'y' also change list 'x'?
429------------------------------------------------
430
431If you wrote code like::
432
433 >>> x = []
434 >>> y = x
435 >>> y.append(10)
436 >>> y
437 [10]
438 >>> x
439 [10]
440
441you might be wondering why appending an element to ``y`` changed ``x`` too.
442
443There are two factors that produce this result:
444
4451) Variables are simply names that refer to objects. Doing ``y = x`` doesn't
446 create a copy of the list -- it creates a new variable ``y`` that refers to
447 the same object ``x`` refers to. This means that there is only one object
448 (the list), and both ``x`` and ``y`` refer to it.
4492) Lists are :term:`mutable`, which means that you can change their content.
450
451After the call to :meth:`~list.append`, the content of the mutable object has
452changed from ``[]`` to ``[10]``. Since both the variables refer to the same
R David Murray12dc0d92014-09-29 10:17:28 -0400453object, using either name accesses the modified value ``[10]``.
R David Murray623ae292014-09-28 11:01:11 -0400454
455If we instead assign an immutable object to ``x``::
456
457 >>> x = 5 # ints are immutable
458 >>> y = x
459 >>> x = x + 1 # 5 can't be mutated, we are creating a new object here
460 >>> x
461 6
462 >>> y
463 5
464
465we can see that in this case ``x`` and ``y`` are not equal anymore. This is
466because integers are :term:`immutable`, and when we do ``x = x + 1`` we are not
467mutating the int ``5`` by incrementing its value; instead, we are creating a
468new object (the int ``6``) and assigning it to ``x`` (that is, changing which
469object ``x`` refers to). After this assignment we have two objects (the ints
470``6`` and ``5``) and two variables that refer to them (``x`` now refers to
471``6`` but ``y`` still refers to ``5``).
472
473Some operations (for example ``y.append(10)`` and ``y.sort()``) mutate the
474object, whereas superficially similar operations (for example ``y = y + [10]``
475and ``sorted(y)``) create a new object. In general in Python (and in all cases
476in the standard library) a method that mutates an object will return ``None``
477to help avoid getting the two types of operations confused. So if you
478mistakenly write ``y.sort()`` thinking it will give you a sorted copy of ``y``,
479you'll instead end up with ``None``, which will likely cause your program to
480generate an easily diagnosed error.
481
482However, there is one class of operations where the same operation sometimes
483has different behaviors with different types: the augmented assignment
484operators. For example, ``+=`` mutates lists but not tuples or ints (``a_list
485+= [1, 2, 3]`` is equivalent to ``a_list.extend([1, 2, 3])`` and mutates
486``a_list``, whereas ``some_tuple += (1, 2, 3)`` and ``some_int += 1`` create
487new objects).
488
489In other words:
490
491* If we have a mutable object (:class:`list`, :class:`dict`, :class:`set`,
492 etc.), we can use some specific operations to mutate it and all the variables
493 that refer to it will see the change.
494* If we have an immutable object (:class:`str`, :class:`int`, :class:`tuple`,
495 etc.), all the variables that refer to it will always see the same value,
496 but operations that transform that value into a new value always return a new
497 object.
498
499If you want to know if two variables refer to the same object or not, you can
500use the :keyword:`is` operator, or the built-in function :func:`id`.
501
502
Georg Brandld7413152009-10-11 21:25:26 +0000503How do I write a function with output parameters (call by reference)?
504---------------------------------------------------------------------
505
506Remember that arguments are passed by assignment in Python. Since assignment
507just creates references to objects, there's no alias between an argument name in
508the caller and callee, and so no call-by-reference per se. You can achieve the
509desired effect in a number of ways.
510
5111) By returning a tuple of the results::
512
513 def func2(a, b):
514 a = 'new-value' # a and b are local names
515 b = b + 1 # assigned to new objects
516 return a, b # return new values
517
518 x, y = 'old-value', 99
519 x, y = func2(x, y)
Georg Brandl62eaaf62009-12-19 17:51:41 +0000520 print(x, y) # output: new-value 100
Georg Brandld7413152009-10-11 21:25:26 +0000521
522 This is almost always the clearest solution.
523
5242) By using global variables. This isn't thread-safe, and is not recommended.
525
5263) By passing a mutable (changeable in-place) object::
527
528 def func1(a):
529 a[0] = 'new-value' # 'a' references a mutable list
530 a[1] = a[1] + 1 # changes a shared object
531
532 args = ['old-value', 99]
533 func1(args)
Georg Brandl62eaaf62009-12-19 17:51:41 +0000534 print(args[0], args[1]) # output: new-value 100
Georg Brandld7413152009-10-11 21:25:26 +0000535
5364) By passing in a dictionary that gets mutated::
537
538 def func3(args):
539 args['a'] = 'new-value' # args is a mutable dictionary
540 args['b'] = args['b'] + 1 # change it in-place
541
Serhiy Storchakadba90392016-05-10 12:01:23 +0300542 args = {'a': 'old-value', 'b': 99}
Georg Brandld7413152009-10-11 21:25:26 +0000543 func3(args)
Georg Brandl62eaaf62009-12-19 17:51:41 +0000544 print(args['a'], args['b'])
Georg Brandld7413152009-10-11 21:25:26 +0000545
5465) Or bundle up values in a class instance::
547
548 class callByRef:
549 def __init__(self, **args):
550 for (key, value) in args.items():
551 setattr(self, key, value)
552
553 def func4(args):
554 args.a = 'new-value' # args is a mutable callByRef
555 args.b = args.b + 1 # change object in-place
556
557 args = callByRef(a='old-value', b=99)
558 func4(args)
Georg Brandl62eaaf62009-12-19 17:51:41 +0000559 print(args.a, args.b)
Georg Brandld7413152009-10-11 21:25:26 +0000560
561
562 There's almost never a good reason to get this complicated.
563
564Your best choice is to return a tuple containing the multiple results.
565
566
567How do you make a higher order function in Python?
568--------------------------------------------------
569
570You have two choices: you can use nested scopes or you can use callable objects.
571For example, suppose you wanted to define ``linear(a,b)`` which returns a
572function ``f(x)`` that computes the value ``a*x+b``. Using nested scopes::
573
574 def linear(a, b):
575 def result(x):
576 return a * x + b
577 return result
578
579Or using a callable object::
580
581 class linear:
582
583 def __init__(self, a, b):
584 self.a, self.b = a, b
585
586 def __call__(self, x):
587 return self.a * x + self.b
588
589In both cases, ::
590
591 taxes = linear(0.3, 2)
592
593gives a callable object where ``taxes(10e6) == 0.3 * 10e6 + 2``.
594
595The callable object approach has the disadvantage that it is a bit slower and
596results in slightly longer code. However, note that a collection of callables
597can share their signature via inheritance::
598
599 class exponential(linear):
600 # __init__ inherited
601 def __call__(self, x):
602 return self.a * (x ** self.b)
603
604Object can encapsulate state for several methods::
605
606 class counter:
607
608 value = 0
609
610 def set(self, x):
611 self.value = x
612
613 def up(self):
614 self.value = self.value + 1
615
616 def down(self):
617 self.value = self.value - 1
618
619 count = counter()
620 inc, dec, reset = count.up, count.down, count.set
621
622Here ``inc()``, ``dec()`` and ``reset()`` act like functions which share the
623same counting variable.
624
625
626How do I copy an object in Python?
627----------------------------------
628
629In general, try :func:`copy.copy` or :func:`copy.deepcopy` for the general case.
630Not all objects can be copied, but most can.
631
632Some objects can be copied more easily. Dictionaries have a :meth:`~dict.copy`
633method::
634
635 newdict = olddict.copy()
636
637Sequences can be copied by slicing::
638
639 new_l = l[:]
640
641
642How can I find the methods or attributes of an object?
643------------------------------------------------------
644
645For an instance x of a user-defined class, ``dir(x)`` returns an alphabetized
646list of the names containing the instance attributes and methods and attributes
647defined by its class.
648
649
650How can my code discover the name of an object?
651-----------------------------------------------
652
653Generally speaking, it can't, because objects don't really have names.
654Essentially, assignment always binds a name to a value; The same is true of
655``def`` and ``class`` statements, but in that case the value is a
656callable. Consider the following code::
657
Serhiy Storchakadba90392016-05-10 12:01:23 +0300658 >>> class A:
659 ... pass
660 ...
661 >>> B = A
662 >>> a = B()
663 >>> b = a
664 >>> print(b)
Georg Brandl62eaaf62009-12-19 17:51:41 +0000665 <__main__.A object at 0x16D07CC>
Serhiy Storchakadba90392016-05-10 12:01:23 +0300666 >>> print(a)
Georg Brandl62eaaf62009-12-19 17:51:41 +0000667 <__main__.A object at 0x16D07CC>
Georg Brandld7413152009-10-11 21:25:26 +0000668
669Arguably the class has a name: even though it is bound to two names and invoked
670through the name B the created instance is still reported as an instance of
671class A. However, it is impossible to say whether the instance's name is a or
672b, since both names are bound to the same value.
673
674Generally speaking it should not be necessary for your code to "know the names"
675of particular values. Unless you are deliberately writing introspective
676programs, this is usually an indication that a change of approach might be
677beneficial.
678
679In comp.lang.python, Fredrik Lundh once gave an excellent analogy in answer to
680this question:
681
682 The same way as you get the name of that cat you found on your porch: the cat
683 (object) itself cannot tell you its name, and it doesn't really care -- so
684 the only way to find out what it's called is to ask all your neighbours
685 (namespaces) if it's their cat (object)...
686
687 ....and don't be surprised if you'll find that it's known by many names, or
688 no name at all!
689
690
691What's up with the comma operator's precedence?
692-----------------------------------------------
693
694Comma is not an operator in Python. Consider this session::
695
696 >>> "a" in "b", "a"
Georg Brandl62eaaf62009-12-19 17:51:41 +0000697 (False, 'a')
Georg Brandld7413152009-10-11 21:25:26 +0000698
699Since the comma is not an operator, but a separator between expressions the
700above is evaluated as if you had entered::
701
R David Murrayfdf95032013-06-19 16:58:26 -0400702 ("a" in "b"), "a"
Georg Brandld7413152009-10-11 21:25:26 +0000703
704not::
705
R David Murrayfdf95032013-06-19 16:58:26 -0400706 "a" in ("b", "a")
Georg Brandld7413152009-10-11 21:25:26 +0000707
708The same is true of the various assignment operators (``=``, ``+=`` etc). They
709are not truly operators but syntactic delimiters in assignment statements.
710
711
712Is there an equivalent of C's "?:" ternary operator?
713----------------------------------------------------
714
Antoine Pitrouc5b266e2011-12-03 22:11:11 +0100715Yes, there is. The syntax is as follows::
Georg Brandld7413152009-10-11 21:25:26 +0000716
717 [on_true] if [expression] else [on_false]
718
719 x, y = 50, 25
Georg Brandld7413152009-10-11 21:25:26 +0000720 small = x if x < y else y
721
Antoine Pitrouc5b266e2011-12-03 22:11:11 +0100722Before this syntax was introduced in Python 2.5, a common idiom was to use
723logical operators::
Georg Brandld7413152009-10-11 21:25:26 +0000724
Antoine Pitrouc5b266e2011-12-03 22:11:11 +0100725 [expression] and [on_true] or [on_false]
Georg Brandld7413152009-10-11 21:25:26 +0000726
Antoine Pitrouc5b266e2011-12-03 22:11:11 +0100727However, this idiom is unsafe, as it can give wrong results when *on_true*
728has a false boolean value. Therefore, it is always better to use
729the ``... if ... else ...`` form.
Georg Brandld7413152009-10-11 21:25:26 +0000730
731
732Is it possible to write obfuscated one-liners in Python?
733--------------------------------------------------------
734
735Yes. Usually this is done by nesting :keyword:`lambda` within
736:keyword:`lambda`. See the following three examples, due to Ulf Bartelt::
737
Georg Brandl62eaaf62009-12-19 17:51:41 +0000738 from functools import reduce
739
Georg Brandld7413152009-10-11 21:25:26 +0000740 # Primes < 1000
Georg Brandl62eaaf62009-12-19 17:51:41 +0000741 print(list(filter(None,map(lambda y:y*reduce(lambda x,y:x*y!=0,
742 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 +0000743
744 # First 10 Fibonacci numbers
Georg Brandl62eaaf62009-12-19 17:51:41 +0000745 print(list(map(lambda x,f=lambda x,f:(f(x-1,f)+f(x-2,f)) if x>1 else 1:
746 f(x,f), range(10))))
Georg Brandld7413152009-10-11 21:25:26 +0000747
748 # Mandelbrot set
Georg Brandl62eaaf62009-12-19 17:51:41 +0000749 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 +0000750 Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,Sy=Sy,L=lambda yc,Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,i=IM,
751 Sx=Sx,Sy=Sy:reduce(lambda x,y:x+y,map(lambda x,xc=Ru,yc=yc,Ru=Ru,Ro=Ro,
752 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
753 >=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(
754 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 +0000755 ))))(-2.1, 0.7, -1.2, 1.2, 30, 80, 24))
Georg Brandld7413152009-10-11 21:25:26 +0000756 # \___ ___/ \___ ___/ | | |__ lines on screen
757 # V V | |______ columns on screen
758 # | | |__________ maximum of "iterations"
759 # | |_________________ range on y axis
760 # |____________________________ range on x axis
761
762Don't try this at home, kids!
763
764
765Numbers and strings
766===================
767
768How do I specify hexadecimal and octal integers?
769------------------------------------------------
770
Georg Brandl62eaaf62009-12-19 17:51:41 +0000771To specify an octal digit, precede the octal value with a zero, and then a lower
772or uppercase "o". For example, to set the variable "a" to the octal value "10"
773(8 in decimal), type::
Georg Brandld7413152009-10-11 21:25:26 +0000774
Georg Brandl62eaaf62009-12-19 17:51:41 +0000775 >>> a = 0o10
Georg Brandld7413152009-10-11 21:25:26 +0000776 >>> a
777 8
778
779Hexadecimal is just as easy. Simply precede the hexadecimal number with a zero,
780and then a lower or uppercase "x". Hexadecimal digits can be specified in lower
781or uppercase. For example, in the Python interpreter::
782
783 >>> a = 0xa5
784 >>> a
785 165
786 >>> b = 0XB2
787 >>> b
788 178
789
790
Georg Brandl62eaaf62009-12-19 17:51:41 +0000791Why does -22 // 10 return -3?
792-----------------------------
Georg Brandld7413152009-10-11 21:25:26 +0000793
794It's primarily driven by the desire that ``i % j`` have the same sign as ``j``.
795If you want that, and also want::
796
Georg Brandl62eaaf62009-12-19 17:51:41 +0000797 i == (i // j) * j + (i % j)
Georg Brandld7413152009-10-11 21:25:26 +0000798
799then integer division has to return the floor. C also requires that identity to
Georg Brandl62eaaf62009-12-19 17:51:41 +0000800hold, and then compilers that truncate ``i // j`` need to make ``i % j`` have
801the same sign as ``i``.
Georg Brandld7413152009-10-11 21:25:26 +0000802
803There are few real use cases for ``i % j`` when ``j`` is negative. When ``j``
804is positive, there are many, and in virtually all of them it's more useful for
805``i % j`` to be ``>= 0``. If the clock says 10 now, what did it say 200 hours
806ago? ``-190 % 12 == 2`` is useful; ``-190 % 12 == -10`` is a bug waiting to
807bite.
808
809
810How do I convert a string to a number?
811--------------------------------------
812
813For integers, use the built-in :func:`int` type constructor, e.g. ``int('144')
814== 144``. Similarly, :func:`float` converts to floating-point,
815e.g. ``float('144') == 144.0``.
816
817By default, these interpret the number as decimal, so that ``int('0144') ==
818144`` and ``int('0x144')`` raises :exc:`ValueError`. ``int(string, base)`` takes
819the base to convert from as a second optional argument, so ``int('0x144', 16) ==
820324``. If the base is specified as 0, the number is interpreted using Python's
Eric V. Smithfc9a4d82014-04-14 07:41:52 -0400821rules: a leading '0o' indicates octal, and '0x' indicates a hex number.
Georg Brandld7413152009-10-11 21:25:26 +0000822
823Do not use the built-in function :func:`eval` if all you need is to convert
824strings to numbers. :func:`eval` will be significantly slower and it presents a
825security risk: someone could pass you a Python expression that might have
826unwanted side effects. For example, someone could pass
827``__import__('os').system("rm -rf $HOME")`` which would erase your home
828directory.
829
830:func:`eval` also has the effect of interpreting numbers as Python expressions,
Georg Brandl62eaaf62009-12-19 17:51:41 +0000831so that e.g. ``eval('09')`` gives a syntax error because Python does not allow
832leading '0' in a decimal number (except '0').
Georg Brandld7413152009-10-11 21:25:26 +0000833
834
835How do I convert a number to a string?
836--------------------------------------
837
838To convert, e.g., the number 144 to the string '144', use the built-in type
839constructor :func:`str`. If you want a hexadecimal or octal representation, use
Georg Brandl62eaaf62009-12-19 17:51:41 +0000840the built-in functions :func:`hex` or :func:`oct`. For fancy formatting, see
Martin Panterd5db1472016-02-08 01:34:09 +0000841the :ref:`formatstrings` section, e.g. ``"{:04d}".format(144)`` yields
Eric V. Smith04d8a242014-04-14 07:52:53 -0400842``'0144'`` and ``"{:.3f}".format(1.0/3.0)`` yields ``'0.333'``.
Georg Brandld7413152009-10-11 21:25:26 +0000843
844
845How do I modify a string in place?
846----------------------------------
847
Antoine Pitrouc5b266e2011-12-03 22:11:11 +0100848You can't, because strings are immutable. In most situations, you should
849simply construct a new string from the various parts you want to assemble
850it from. However, if you need an object with the ability to modify in-place
Martin Panter7462b6492015-11-02 03:37:02 +0000851unicode data, try using an :class:`io.StringIO` object or the :mod:`array`
Antoine Pitrouc5b266e2011-12-03 22:11:11 +0100852module::
Georg Brandld7413152009-10-11 21:25:26 +0000853
R David Murrayfdf95032013-06-19 16:58:26 -0400854 >>> import io
Georg Brandld7413152009-10-11 21:25:26 +0000855 >>> s = "Hello, world"
Antoine Pitrouc5b266e2011-12-03 22:11:11 +0100856 >>> sio = io.StringIO(s)
857 >>> sio.getvalue()
858 'Hello, world'
859 >>> sio.seek(7)
860 7
861 >>> sio.write("there!")
862 6
863 >>> sio.getvalue()
Georg Brandld7413152009-10-11 21:25:26 +0000864 'Hello, there!'
865
866 >>> import array
Georg Brandl62eaaf62009-12-19 17:51:41 +0000867 >>> a = array.array('u', s)
868 >>> print(a)
869 array('u', 'Hello, world')
870 >>> a[0] = 'y'
871 >>> print(a)
R David Murrayfdf95032013-06-19 16:58:26 -0400872 array('u', 'yello, world')
Georg Brandl62eaaf62009-12-19 17:51:41 +0000873 >>> a.tounicode()
Georg Brandld7413152009-10-11 21:25:26 +0000874 'yello, world'
875
876
877How do I use strings to call functions/methods?
878-----------------------------------------------
879
880There are various techniques.
881
882* The best is to use a dictionary that maps strings to functions. The primary
883 advantage of this technique is that the strings do not need to match the names
884 of the functions. This is also the primary technique used to emulate a case
885 construct::
886
887 def a():
888 pass
889
890 def b():
891 pass
892
893 dispatch = {'go': a, 'stop': b} # Note lack of parens for funcs
894
895 dispatch[get_input()]() # Note trailing parens to call function
896
897* Use the built-in function :func:`getattr`::
898
899 import foo
900 getattr(foo, 'bar')()
901
902 Note that :func:`getattr` works on any object, including classes, class
903 instances, modules, and so on.
904
905 This is used in several places in the standard library, like this::
906
907 class Foo:
908 def do_foo(self):
909 ...
910
911 def do_bar(self):
912 ...
913
914 f = getattr(foo_instance, 'do_' + opname)
915 f()
916
917
918* Use :func:`locals` or :func:`eval` to resolve the function name::
919
920 def myFunc():
Georg Brandl62eaaf62009-12-19 17:51:41 +0000921 print("hello")
Georg Brandld7413152009-10-11 21:25:26 +0000922
923 fname = "myFunc"
924
925 f = locals()[fname]
926 f()
927
928 f = eval(fname)
929 f()
930
931 Note: Using :func:`eval` is slow and dangerous. If you don't have absolute
932 control over the contents of the string, someone could pass a string that
933 resulted in an arbitrary function being executed.
934
935Is there an equivalent to Perl's chomp() for removing trailing newlines from strings?
936-------------------------------------------------------------------------------------
937
Antoine Pitrouf3520402011-12-03 22:19:55 +0100938You can use ``S.rstrip("\r\n")`` to remove all occurrences of any line
939terminator from the end of the string ``S`` without removing other trailing
940whitespace. If the string ``S`` represents more than one line, with several
941empty lines at the end, the line terminators for all the blank lines will
942be removed::
Georg Brandld7413152009-10-11 21:25:26 +0000943
944 >>> lines = ("line 1 \r\n"
945 ... "\r\n"
946 ... "\r\n")
947 >>> lines.rstrip("\n\r")
Georg Brandl62eaaf62009-12-19 17:51:41 +0000948 'line 1 '
Georg Brandld7413152009-10-11 21:25:26 +0000949
950Since this is typically only desired when reading text one line at a time, using
951``S.rstrip()`` this way works well.
952
Georg Brandld7413152009-10-11 21:25:26 +0000953
954Is there a scanf() or sscanf() equivalent?
955------------------------------------------
956
957Not as such.
958
959For simple input parsing, the easiest approach is usually to split the line into
960whitespace-delimited words using the :meth:`~str.split` method of string objects
961and then convert decimal strings to numeric values using :func:`int` or
962:func:`float`. ``split()`` supports an optional "sep" parameter which is useful
963if the line uses something other than whitespace as a separator.
964
Brian Curtin5a7a52f2010-09-23 13:45:21 +0000965For more complicated input parsing, regular expressions are more powerful
Georg Brandl60203b42010-10-06 10:11:56 +0000966than C's :c:func:`sscanf` and better suited for the task.
Georg Brandld7413152009-10-11 21:25:26 +0000967
968
Georg Brandl62eaaf62009-12-19 17:51:41 +0000969What does 'UnicodeDecodeError' or 'UnicodeEncodeError' error mean?
970-------------------------------------------------------------------
Georg Brandld7413152009-10-11 21:25:26 +0000971
Georg Brandl62eaaf62009-12-19 17:51:41 +0000972See the :ref:`unicode-howto`.
Georg Brandld7413152009-10-11 21:25:26 +0000973
974
Antoine Pitrou432259f2011-12-09 23:10:31 +0100975Performance
976===========
977
978My program is too slow. How do I speed it up?
979---------------------------------------------
980
981That's a tough one, in general. First, here are a list of things to
982remember before diving further:
983
Georg Brandl300a6912012-03-14 22:40:08 +0100984* Performance characteristics vary across Python implementations. This FAQ
Antoine Pitrou432259f2011-12-09 23:10:31 +0100985 focusses on :term:`CPython`.
Georg Brandl300a6912012-03-14 22:40:08 +0100986* Behaviour can vary across operating systems, especially when talking about
Antoine Pitrou432259f2011-12-09 23:10:31 +0100987 I/O or multi-threading.
988* You should always find the hot spots in your program *before* attempting to
989 optimize any code (see the :mod:`profile` module).
990* Writing benchmark scripts will allow you to iterate quickly when searching
991 for improvements (see the :mod:`timeit` module).
992* It is highly recommended to have good code coverage (through unit testing
993 or any other technique) before potentially introducing regressions hidden
994 in sophisticated optimizations.
995
996That being said, there are many tricks to speed up Python code. Here are
997some general principles which go a long way towards reaching acceptable
998performance levels:
999
1000* Making your algorithms faster (or changing to faster ones) can yield
1001 much larger benefits than trying to sprinkle micro-optimization tricks
1002 all over your code.
1003
1004* Use the right data structures. Study documentation for the :ref:`bltin-types`
1005 and the :mod:`collections` module.
1006
1007* When the standard library provides a primitive for doing something, it is
1008 likely (although not guaranteed) to be faster than any alternative you
1009 may come up with. This is doubly true for primitives written in C, such
1010 as builtins and some extension types. For example, be sure to use
1011 either the :meth:`list.sort` built-in method or the related :func:`sorted`
Senthil Kumarand03d1d42016-01-01 23:25:58 -08001012 function to do sorting (and see the :ref:`sortinghowto` for examples
Antoine Pitrou432259f2011-12-09 23:10:31 +01001013 of moderately advanced usage).
1014
1015* Abstractions tend to create indirections and force the interpreter to work
1016 more. If the levels of indirection outweigh the amount of useful work
1017 done, your program will be slower. You should avoid excessive abstraction,
1018 especially under the form of tiny functions or methods (which are also often
1019 detrimental to readability).
1020
1021If you have reached the limit of what pure Python can allow, there are tools
1022to take you further away. For example, `Cython <http://cython.org>`_ can
1023compile a slightly modified version of Python code into a C extension, and
1024can be used on many different platforms. Cython can take advantage of
1025compilation (and optional type annotations) to make your code significantly
1026faster than when interpreted. If you are confident in your C programming
1027skills, you can also :ref:`write a C extension module <extending-index>`
1028yourself.
1029
1030.. seealso::
1031 The wiki page devoted to `performance tips
Georg Brandle73778c2014-10-29 08:36:35 +01001032 <https://wiki.python.org/moin/PythonSpeed/PerformanceTips>`_.
Antoine Pitrou432259f2011-12-09 23:10:31 +01001033
1034.. _efficient_string_concatenation:
1035
Antoine Pitroufd9ebd42011-11-25 16:33:53 +01001036What is the most efficient way to concatenate many strings together?
1037--------------------------------------------------------------------
1038
1039:class:`str` and :class:`bytes` objects are immutable, therefore concatenating
1040many strings together is inefficient as each concatenation creates a new
1041object. In the general case, the total runtime cost is quadratic in the
1042total string length.
1043
1044To accumulate many :class:`str` objects, the recommended idiom is to place
1045them into a list and call :meth:`str.join` at the end::
1046
1047 chunks = []
1048 for s in my_strings:
1049 chunks.append(s)
1050 result = ''.join(chunks)
1051
1052(another reasonably efficient idiom is to use :class:`io.StringIO`)
1053
1054To accumulate many :class:`bytes` objects, the recommended idiom is to extend
1055a :class:`bytearray` object using in-place concatenation (the ``+=`` operator)::
1056
1057 result = bytearray()
1058 for b in my_bytes_objects:
1059 result += b
1060
1061
Georg Brandld7413152009-10-11 21:25:26 +00001062Sequences (Tuples/Lists)
1063========================
1064
1065How do I convert between tuples and lists?
1066------------------------------------------
1067
1068The type constructor ``tuple(seq)`` converts any sequence (actually, any
1069iterable) into a tuple with the same items in the same order.
1070
1071For example, ``tuple([1, 2, 3])`` yields ``(1, 2, 3)`` and ``tuple('abc')``
1072yields ``('a', 'b', 'c')``. If the argument is a tuple, it does not make a copy
1073but returns the same object, so it is cheap to call :func:`tuple` when you
1074aren't sure that an object is already a tuple.
1075
1076The type constructor ``list(seq)`` converts any sequence or iterable into a list
1077with the same items in the same order. For example, ``list((1, 2, 3))`` yields
1078``[1, 2, 3]`` and ``list('abc')`` yields ``['a', 'b', 'c']``. If the argument
1079is a list, it makes a copy just like ``seq[:]`` would.
1080
1081
1082What's a negative index?
1083------------------------
1084
1085Python sequences are indexed with positive numbers and negative numbers. For
1086positive numbers 0 is the first index 1 is the second index and so forth. For
1087negative indices -1 is the last index and -2 is the penultimate (next to last)
1088index and so forth. Think of ``seq[-n]`` as the same as ``seq[len(seq)-n]``.
1089
1090Using negative indices can be very convenient. For example ``S[:-1]`` is all of
1091the string except for its last character, which is useful for removing the
1092trailing newline from a string.
1093
1094
1095How do I iterate over a sequence in reverse order?
1096--------------------------------------------------
1097
Georg Brandlc4a55fc2010-02-06 18:46:57 +00001098Use the :func:`reversed` built-in function, which is new in Python 2.4::
Georg Brandld7413152009-10-11 21:25:26 +00001099
1100 for x in reversed(sequence):
Serhiy Storchakadba90392016-05-10 12:01:23 +03001101 ... # do something with x ...
Georg Brandld7413152009-10-11 21:25:26 +00001102
1103This won't touch your original sequence, but build a new copy with reversed
1104order to iterate over.
1105
1106With Python 2.3, you can use an extended slice syntax::
1107
1108 for x in sequence[::-1]:
Serhiy Storchakadba90392016-05-10 12:01:23 +03001109 ... # do something with x ...
Georg Brandld7413152009-10-11 21:25:26 +00001110
1111
1112How do you remove duplicates from a list?
1113-----------------------------------------
1114
1115See the Python Cookbook for a long discussion of many ways to do this:
1116
Serhiy Storchaka6dff0202016-05-07 10:49:07 +03001117 https://code.activestate.com/recipes/52560/
Georg Brandld7413152009-10-11 21:25:26 +00001118
1119If you don't mind reordering the list, sort it and then scan from the end of the
1120list, deleting duplicates as you go::
1121
Georg Brandl62eaaf62009-12-19 17:51:41 +00001122 if mylist:
1123 mylist.sort()
1124 last = mylist[-1]
1125 for i in range(len(mylist)-2, -1, -1):
1126 if last == mylist[i]:
1127 del mylist[i]
Georg Brandld7413152009-10-11 21:25:26 +00001128 else:
Georg Brandl62eaaf62009-12-19 17:51:41 +00001129 last = mylist[i]
Georg Brandld7413152009-10-11 21:25:26 +00001130
Antoine Pitrouf3520402011-12-03 22:19:55 +01001131If all elements of the list may be used as set keys (i.e. they are all
1132:term:`hashable`) this is often faster ::
Georg Brandld7413152009-10-11 21:25:26 +00001133
Georg Brandl62eaaf62009-12-19 17:51:41 +00001134 mylist = list(set(mylist))
Georg Brandld7413152009-10-11 21:25:26 +00001135
1136This converts the list into a set, thereby removing duplicates, and then back
1137into a list.
1138
1139
1140How do you make an array in Python?
1141-----------------------------------
1142
1143Use a list::
1144
1145 ["this", 1, "is", "an", "array"]
1146
1147Lists are equivalent to C or Pascal arrays in their time complexity; the primary
1148difference is that a Python list can contain objects of many different types.
1149
1150The ``array`` module also provides methods for creating arrays of fixed types
1151with compact representations, but they are slower to index than lists. Also
1152note that the Numeric extensions and others define array-like structures with
1153various characteristics as well.
1154
1155To get Lisp-style linked lists, you can emulate cons cells using tuples::
1156
1157 lisp_list = ("like", ("this", ("example", None) ) )
1158
1159If mutability is desired, you could use lists instead of tuples. Here the
1160analogue of lisp car is ``lisp_list[0]`` and the analogue of cdr is
1161``lisp_list[1]``. Only do this if you're sure you really need to, because it's
1162usually a lot slower than using Python lists.
1163
1164
Martin Panter7f02d6d2015-09-07 02:08:55 +00001165.. _faq-multidimensional-list:
1166
Georg Brandld7413152009-10-11 21:25:26 +00001167How do I create a multidimensional list?
1168----------------------------------------
1169
1170You probably tried to make a multidimensional array like this::
1171
R David Murrayfdf95032013-06-19 16:58:26 -04001172 >>> A = [[None] * 2] * 3
Georg Brandld7413152009-10-11 21:25:26 +00001173
Senthil Kumaran77493202016-06-04 20:07:34 -07001174This looks correct if you print it:
1175
1176.. testsetup::
1177
1178 A = [[None] * 2] * 3
1179
1180.. doctest::
Georg Brandld7413152009-10-11 21:25:26 +00001181
1182 >>> A
1183 [[None, None], [None, None], [None, None]]
1184
1185But when you assign a value, it shows up in multiple places:
1186
Senthil Kumaran77493202016-06-04 20:07:34 -07001187.. testsetup::
1188
1189 A = [[None] * 2] * 3
1190
1191.. doctest::
1192
1193 >>> A[0][0] = 5
1194 >>> A
1195 [[5, None], [5, None], [5, None]]
Georg Brandld7413152009-10-11 21:25:26 +00001196
1197The reason is that replicating a list with ``*`` doesn't create copies, it only
1198creates references to the existing objects. The ``*3`` creates a list
1199containing 3 references to the same list of length two. Changes to one row will
1200show in all rows, which is almost certainly not what you want.
1201
1202The suggested approach is to create a list of the desired length first and then
1203fill in each element with a newly created list::
1204
1205 A = [None] * 3
1206 for i in range(3):
1207 A[i] = [None] * 2
1208
1209This generates a list containing 3 different lists of length two. You can also
1210use a list comprehension::
1211
1212 w, h = 2, 3
1213 A = [[None] * w for i in range(h)]
1214
Benjamin Peterson6d3ad2f2016-05-26 22:51:32 -07001215Or, you can use an extension that provides a matrix datatype; `NumPy
Ezio Melottic1f58392013-06-09 01:04:21 +03001216<http://www.numpy.org/>`_ is the best known.
Georg Brandld7413152009-10-11 21:25:26 +00001217
1218
1219How do I apply a method to a sequence of objects?
1220-------------------------------------------------
1221
1222Use a list comprehension::
1223
Georg Brandl62eaaf62009-12-19 17:51:41 +00001224 result = [obj.method() for obj in mylist]
Georg Brandld7413152009-10-11 21:25:26 +00001225
Larry Hastings3732ed22014-03-15 21:13:56 -07001226.. _faq-augmented-assignment-tuple-error:
Georg Brandld7413152009-10-11 21:25:26 +00001227
R David Murraybcf06d32013-05-20 10:32:46 -04001228Why does a_tuple[i] += ['item'] raise an exception when the addition works?
1229---------------------------------------------------------------------------
1230
1231This is because of a combination of the fact that augmented assignment
1232operators are *assignment* operators, and the difference between mutable and
1233immutable objects in Python.
1234
1235This discussion applies in general when augmented assignment operators are
1236applied to elements of a tuple that point to mutable objects, but we'll use
1237a ``list`` and ``+=`` as our exemplar.
1238
1239If you wrote::
1240
1241 >>> a_tuple = (1, 2)
1242 >>> a_tuple[0] += 1
1243 Traceback (most recent call last):
1244 ...
1245 TypeError: 'tuple' object does not support item assignment
1246
1247The reason for the exception should be immediately clear: ``1`` is added to the
1248object ``a_tuple[0]`` points to (``1``), producing the result object, ``2``,
1249but when we attempt to assign the result of the computation, ``2``, to element
1250``0`` of the tuple, we get an error because we can't change what an element of
1251a tuple points to.
1252
1253Under the covers, what this augmented assignment statement is doing is
1254approximately this::
1255
R David Murray95ae9922013-05-21 11:44:41 -04001256 >>> result = a_tuple[0] + 1
R David Murraybcf06d32013-05-20 10:32:46 -04001257 >>> a_tuple[0] = result
1258 Traceback (most recent call last):
1259 ...
1260 TypeError: 'tuple' object does not support item assignment
1261
1262It is the assignment part of the operation that produces the error, since a
1263tuple is immutable.
1264
1265When you write something like::
1266
1267 >>> a_tuple = (['foo'], 'bar')
1268 >>> a_tuple[0] += ['item']
1269 Traceback (most recent call last):
1270 ...
1271 TypeError: 'tuple' object does not support item assignment
1272
1273The exception is a bit more surprising, and even more surprising is the fact
1274that even though there was an error, the append worked::
1275
1276 >>> a_tuple[0]
1277 ['foo', 'item']
1278
R David Murray95ae9922013-05-21 11:44:41 -04001279To see why this happens, you need to know that (a) if an object implements an
1280``__iadd__`` magic method, it gets called when the ``+=`` augmented assignment
1281is executed, and its return value is what gets used in the assignment statement;
1282and (b) for lists, ``__iadd__`` is equivalent to calling ``extend`` on the list
1283and returning the list. That's why we say that for lists, ``+=`` is a
1284"shorthand" for ``list.extend``::
R David Murraybcf06d32013-05-20 10:32:46 -04001285
1286 >>> a_list = []
1287 >>> a_list += [1]
1288 >>> a_list
1289 [1]
1290
R David Murray95ae9922013-05-21 11:44:41 -04001291This is equivalent to::
R David Murraybcf06d32013-05-20 10:32:46 -04001292
1293 >>> result = a_list.__iadd__([1])
1294 >>> a_list = result
1295
1296The object pointed to by a_list has been mutated, and the pointer to the
1297mutated object is assigned back to ``a_list``. The end result of the
1298assignment is a no-op, since it is a pointer to the same object that ``a_list``
1299was previously pointing to, but the assignment still happens.
1300
1301Thus, in our tuple example what is happening is equivalent to::
1302
1303 >>> result = a_tuple[0].__iadd__(['item'])
1304 >>> a_tuple[0] = result
1305 Traceback (most recent call last):
1306 ...
1307 TypeError: 'tuple' object does not support item assignment
1308
1309The ``__iadd__`` succeeds, and thus the list is extended, but even though
1310``result`` points to the same object that ``a_tuple[0]`` already points to,
1311that final assignment still results in an error, because tuples are immutable.
1312
1313
Georg Brandld7413152009-10-11 21:25:26 +00001314Dictionaries
1315============
1316
Benjamin Petersonb152e172013-11-26 23:05:25 -06001317How can I get a dictionary to store and display its keys in a consistent order?
1318-------------------------------------------------------------------------------
Georg Brandld7413152009-10-11 21:25:26 +00001319
Benjamin Petersonb152e172013-11-26 23:05:25 -06001320Use :class:`collections.OrderedDict`.
Georg Brandld7413152009-10-11 21:25:26 +00001321
1322I want to do a complicated sort: can you do a Schwartzian Transform in Python?
1323------------------------------------------------------------------------------
1324
1325The technique, attributed to Randal Schwartz of the Perl community, sorts the
1326elements of a list by a metric which maps each element to its "sort value". In
Berker Peksag5b6a14d2016-06-01 13:54:33 -07001327Python, use the ``key`` argument for the :meth:`list.sort` method::
Georg Brandld7413152009-10-11 21:25:26 +00001328
1329 Isorted = L[:]
1330 Isorted.sort(key=lambda s: int(s[10:15]))
1331
Georg Brandld7413152009-10-11 21:25:26 +00001332
1333How can I sort one list by values from another list?
1334----------------------------------------------------
1335
Georg Brandl62eaaf62009-12-19 17:51:41 +00001336Merge them into an iterator of tuples, sort the resulting list, and then pick
Georg Brandld7413152009-10-11 21:25:26 +00001337out the element you want. ::
1338
1339 >>> list1 = ["what", "I'm", "sorting", "by"]
1340 >>> list2 = ["something", "else", "to", "sort"]
1341 >>> pairs = zip(list1, list2)
Georg Brandl62eaaf62009-12-19 17:51:41 +00001342 >>> pairs = sorted(pairs)
Georg Brandld7413152009-10-11 21:25:26 +00001343 >>> pairs
Georg Brandl62eaaf62009-12-19 17:51:41 +00001344 [("I'm", 'else'), ('by', 'sort'), ('sorting', 'to'), ('what', 'something')]
1345 >>> result = [x[1] for x in pairs]
Georg Brandld7413152009-10-11 21:25:26 +00001346 >>> result
1347 ['else', 'sort', 'to', 'something']
1348
Georg Brandl62eaaf62009-12-19 17:51:41 +00001349
Georg Brandld7413152009-10-11 21:25:26 +00001350An alternative for the last step is::
1351
Georg Brandl62eaaf62009-12-19 17:51:41 +00001352 >>> result = []
1353 >>> for p in pairs: result.append(p[1])
Georg Brandld7413152009-10-11 21:25:26 +00001354
1355If you find this more legible, you might prefer to use this instead of the final
1356list comprehension. However, it is almost twice as slow for long lists. Why?
1357First, the ``append()`` operation has to reallocate memory, and while it uses
1358some tricks to avoid doing that each time, it still has to do it occasionally,
1359and that costs quite a bit. Second, the expression "result.append" requires an
1360extra attribute lookup, and third, there's a speed reduction from having to make
1361all those function calls.
1362
1363
1364Objects
1365=======
1366
1367What is a class?
1368----------------
1369
1370A class is the particular object type created by executing a class statement.
1371Class objects are used as templates to create instance objects, which embody
1372both the data (attributes) and code (methods) specific to a datatype.
1373
1374A class can be based on one or more other classes, called its base class(es). It
1375then inherits the attributes and methods of its base classes. This allows an
1376object model to be successively refined by inheritance. You might have a
1377generic ``Mailbox`` class that provides basic accessor methods for a mailbox,
1378and subclasses such as ``MboxMailbox``, ``MaildirMailbox``, ``OutlookMailbox``
1379that handle various specific mailbox formats.
1380
1381
1382What is a method?
1383-----------------
1384
1385A method is a function on some object ``x`` that you normally call as
1386``x.name(arguments...)``. Methods are defined as functions inside the class
1387definition::
1388
1389 class C:
Serhiy Storchakadba90392016-05-10 12:01:23 +03001390 def meth(self, arg):
Georg Brandld7413152009-10-11 21:25:26 +00001391 return arg * 2 + self.attribute
1392
1393
1394What is self?
1395-------------
1396
1397Self is merely a conventional name for the first argument of a method. A method
1398defined as ``meth(self, a, b, c)`` should be called as ``x.meth(a, b, c)`` for
1399some instance ``x`` of the class in which the definition occurs; the called
1400method will think it is called as ``meth(x, a, b, c)``.
1401
1402See also :ref:`why-self`.
1403
1404
1405How do I check if an object is an instance of a given class or of a subclass of it?
1406-----------------------------------------------------------------------------------
1407
1408Use the built-in function ``isinstance(obj, cls)``. You can check if an object
1409is an instance of any of a number of classes by providing a tuple instead of a
1410single class, e.g. ``isinstance(obj, (class1, class2, ...))``, and can also
1411check whether an object is one of Python's built-in types, e.g.
Georg Brandl62eaaf62009-12-19 17:51:41 +00001412``isinstance(obj, str)`` or ``isinstance(obj, (int, float, complex))``.
Georg Brandld7413152009-10-11 21:25:26 +00001413
1414Note that most programs do not use :func:`isinstance` on user-defined classes
1415very often. If you are developing the classes yourself, a more proper
1416object-oriented style is to define methods on the classes that encapsulate a
1417particular behaviour, instead of checking the object's class and doing a
1418different thing based on what class it is. For example, if you have a function
1419that does something::
1420
Georg Brandl62eaaf62009-12-19 17:51:41 +00001421 def search(obj):
Georg Brandld7413152009-10-11 21:25:26 +00001422 if isinstance(obj, Mailbox):
Serhiy Storchakadba90392016-05-10 12:01:23 +03001423 ... # code to search a mailbox
Georg Brandld7413152009-10-11 21:25:26 +00001424 elif isinstance(obj, Document):
Serhiy Storchakadba90392016-05-10 12:01:23 +03001425 ... # code to search a document
Georg Brandld7413152009-10-11 21:25:26 +00001426 elif ...
1427
1428A better approach is to define a ``search()`` method on all the classes and just
1429call it::
1430
1431 class Mailbox:
1432 def search(self):
Serhiy Storchakadba90392016-05-10 12:01:23 +03001433 ... # code to search a mailbox
Georg Brandld7413152009-10-11 21:25:26 +00001434
1435 class Document:
1436 def search(self):
Serhiy Storchakadba90392016-05-10 12:01:23 +03001437 ... # code to search a document
Georg Brandld7413152009-10-11 21:25:26 +00001438
1439 obj.search()
1440
1441
1442What is delegation?
1443-------------------
1444
1445Delegation is an object oriented technique (also called a design pattern).
1446Let's say you have an object ``x`` and want to change the behaviour of just one
1447of its methods. You can create a new class that provides a new implementation
1448of the method you're interested in changing and delegates all other methods to
1449the corresponding method of ``x``.
1450
1451Python programmers can easily implement delegation. For example, the following
1452class implements a class that behaves like a file but converts all written data
1453to uppercase::
1454
1455 class UpperOut:
1456
1457 def __init__(self, outfile):
1458 self._outfile = outfile
1459
1460 def write(self, s):
1461 self._outfile.write(s.upper())
1462
1463 def __getattr__(self, name):
1464 return getattr(self._outfile, name)
1465
1466Here the ``UpperOut`` class redefines the ``write()`` method to convert the
1467argument string to uppercase before calling the underlying
1468``self.__outfile.write()`` method. All other methods are delegated to the
1469underlying ``self.__outfile`` object. The delegation is accomplished via the
1470``__getattr__`` method; consult :ref:`the language reference <attribute-access>`
1471for more information about controlling attribute access.
1472
1473Note that for more general cases delegation can get trickier. When attributes
1474must be set as well as retrieved, the class must define a :meth:`__setattr__`
1475method too, and it must do so carefully. The basic implementation of
1476:meth:`__setattr__` is roughly equivalent to the following::
1477
1478 class X:
1479 ...
1480 def __setattr__(self, name, value):
1481 self.__dict__[name] = value
1482 ...
1483
1484Most :meth:`__setattr__` implementations must modify ``self.__dict__`` to store
1485local state for self without causing an infinite recursion.
1486
1487
1488How do I call a method defined in a base class from a derived class that overrides it?
1489--------------------------------------------------------------------------------------
1490
Georg Brandl62eaaf62009-12-19 17:51:41 +00001491Use the built-in :func:`super` function::
Georg Brandld7413152009-10-11 21:25:26 +00001492
1493 class Derived(Base):
Serhiy Storchakadba90392016-05-10 12:01:23 +03001494 def meth(self):
Georg Brandld7413152009-10-11 21:25:26 +00001495 super(Derived, self).meth()
1496
Georg Brandl62eaaf62009-12-19 17:51:41 +00001497For version prior to 3.0, you may be using classic classes: For a class
1498definition such as ``class Derived(Base): ...`` you can call method ``meth()``
1499defined in ``Base`` (or one of ``Base``'s base classes) as ``Base.meth(self,
1500arguments...)``. Here, ``Base.meth`` is an unbound method, so you need to
1501provide the ``self`` argument.
Georg Brandld7413152009-10-11 21:25:26 +00001502
1503
1504How can I organize my code to make it easier to change the base class?
1505----------------------------------------------------------------------
1506
1507You could define an alias for the base class, assign the real base class to it
1508before your class definition, and use the alias throughout your class. Then all
1509you have to change is the value assigned to the alias. Incidentally, this trick
1510is also handy if you want to decide dynamically (e.g. depending on availability
1511of resources) which base class to use. Example::
1512
1513 BaseAlias = <real base class>
1514
1515 class Derived(BaseAlias):
1516 def meth(self):
1517 BaseAlias.meth(self)
1518 ...
1519
1520
1521How do I create static class data and static class methods?
1522-----------------------------------------------------------
1523
Georg Brandl62eaaf62009-12-19 17:51:41 +00001524Both static data and static methods (in the sense of C++ or Java) are supported
1525in Python.
Georg Brandld7413152009-10-11 21:25:26 +00001526
1527For static data, simply define a class attribute. To assign a new value to the
1528attribute, you have to explicitly use the class name in the assignment::
1529
1530 class C:
1531 count = 0 # number of times C.__init__ called
1532
1533 def __init__(self):
1534 C.count = C.count + 1
1535
1536 def getcount(self):
1537 return C.count # or return self.count
1538
1539``c.count`` also refers to ``C.count`` for any ``c`` such that ``isinstance(c,
1540C)`` holds, unless overridden by ``c`` itself or by some class on the base-class
1541search path from ``c.__class__`` back to ``C``.
1542
1543Caution: within a method of C, an assignment like ``self.count = 42`` creates a
Georg Brandl62eaaf62009-12-19 17:51:41 +00001544new and unrelated instance named "count" in ``self``'s own dict. Rebinding of a
1545class-static data name must always specify the class whether inside a method or
1546not::
Georg Brandld7413152009-10-11 21:25:26 +00001547
1548 C.count = 314
1549
Antoine Pitrouf3520402011-12-03 22:19:55 +01001550Static methods are possible::
Georg Brandld7413152009-10-11 21:25:26 +00001551
1552 class C:
1553 @staticmethod
1554 def static(arg1, arg2, arg3):
1555 # No 'self' parameter!
1556 ...
1557
1558However, a far more straightforward way to get the effect of a static method is
1559via a simple module-level function::
1560
1561 def getcount():
1562 return C.count
1563
1564If your code is structured so as to define one class (or tightly related class
1565hierarchy) per module, this supplies the desired encapsulation.
1566
1567
1568How can I overload constructors (or methods) in Python?
1569-------------------------------------------------------
1570
1571This answer actually applies to all methods, but the question usually comes up
1572first in the context of constructors.
1573
1574In C++ you'd write
1575
1576.. code-block:: c
1577
1578 class C {
1579 C() { cout << "No arguments\n"; }
1580 C(int i) { cout << "Argument is " << i << "\n"; }
1581 }
1582
1583In Python you have to write a single constructor that catches all cases using
1584default arguments. For example::
1585
1586 class C:
1587 def __init__(self, i=None):
1588 if i is None:
Georg Brandl62eaaf62009-12-19 17:51:41 +00001589 print("No arguments")
Georg Brandld7413152009-10-11 21:25:26 +00001590 else:
Georg Brandl62eaaf62009-12-19 17:51:41 +00001591 print("Argument is", i)
Georg Brandld7413152009-10-11 21:25:26 +00001592
1593This is not entirely equivalent, but close enough in practice.
1594
1595You could also try a variable-length argument list, e.g. ::
1596
1597 def __init__(self, *args):
1598 ...
1599
1600The same approach works for all method definitions.
1601
1602
1603I try to use __spam and I get an error about _SomeClassName__spam.
1604------------------------------------------------------------------
1605
1606Variable names with double leading underscores are "mangled" to provide a simple
1607but effective way to define class private variables. Any identifier of the form
1608``__spam`` (at least two leading underscores, at most one trailing underscore)
1609is textually replaced with ``_classname__spam``, where ``classname`` is the
1610current class name with any leading underscores stripped.
1611
1612This doesn't guarantee privacy: an outside user can still deliberately access
1613the "_classname__spam" attribute, and private values are visible in the object's
1614``__dict__``. Many Python programmers never bother to use private variable
1615names at all.
1616
1617
1618My class defines __del__ but it is not called when I delete the object.
1619-----------------------------------------------------------------------
1620
1621There are several possible reasons for this.
1622
1623The del statement does not necessarily call :meth:`__del__` -- it simply
1624decrements the object's reference count, and if this reaches zero
1625:meth:`__del__` is called.
1626
1627If your data structures contain circular links (e.g. a tree where each child has
1628a parent reference and each parent has a list of children) the reference counts
1629will never go back to zero. Once in a while Python runs an algorithm to detect
1630such cycles, but the garbage collector might run some time after the last
1631reference to your data structure vanishes, so your :meth:`__del__` method may be
1632called at an inconvenient and random time. This is inconvenient if you're trying
1633to reproduce a problem. Worse, the order in which object's :meth:`__del__`
1634methods are executed is arbitrary. You can run :func:`gc.collect` to force a
1635collection, but there *are* pathological cases where objects will never be
1636collected.
1637
1638Despite the cycle collector, it's still a good idea to define an explicit
1639``close()`` method on objects to be called whenever you're done with them. The
1640``close()`` method can then remove attributes that refer to subobjecs. Don't
1641call :meth:`__del__` directly -- :meth:`__del__` should call ``close()`` and
1642``close()`` should make sure that it can be called more than once for the same
1643object.
1644
1645Another way to avoid cyclical references is to use the :mod:`weakref` module,
1646which allows you to point to objects without incrementing their reference count.
1647Tree data structures, for instance, should use weak references for their parent
1648and sibling references (if they need them!).
1649
Georg Brandl62eaaf62009-12-19 17:51:41 +00001650.. XXX relevant for Python 3?
1651
1652 If the object has ever been a local variable in a function that caught an
1653 expression in an except clause, chances are that a reference to the object
1654 still exists in that function's stack frame as contained in the stack trace.
1655 Normally, calling :func:`sys.exc_clear` will take care of this by clearing
1656 the last recorded exception.
Georg Brandld7413152009-10-11 21:25:26 +00001657
1658Finally, if your :meth:`__del__` method raises an exception, a warning message
1659is printed to :data:`sys.stderr`.
1660
1661
1662How do I get a list of all instances of a given class?
1663------------------------------------------------------
1664
1665Python does not keep track of all instances of a class (or of a built-in type).
1666You can program the class's constructor to keep track of all instances by
1667keeping a list of weak references to each instance.
1668
1669
Georg Brandld8ede4f2013-10-12 18:14:25 +02001670Why does the result of ``id()`` appear to be not unique?
1671--------------------------------------------------------
1672
1673The :func:`id` builtin returns an integer that is guaranteed to be unique during
1674the lifetime of the object. Since in CPython, this is the object's memory
1675address, it happens frequently that after an object is deleted from memory, the
1676next freshly created object is allocated at the same position in memory. This
1677is illustrated by this example:
1678
Senthil Kumaran77493202016-06-04 20:07:34 -07001679>>> id(1000) # doctest: +SKIP
Georg Brandld8ede4f2013-10-12 18:14:25 +0200168013901272
Senthil Kumaran77493202016-06-04 20:07:34 -07001681>>> id(2000) # doctest: +SKIP
Georg Brandld8ede4f2013-10-12 18:14:25 +0200168213901272
1683
1684The two ids belong to different integer objects that are created before, and
1685deleted immediately after execution of the ``id()`` call. To be sure that
1686objects whose id you want to examine are still alive, create another reference
1687to the object:
1688
1689>>> a = 1000; b = 2000
Senthil Kumaran77493202016-06-04 20:07:34 -07001690>>> id(a) # doctest: +SKIP
Georg Brandld8ede4f2013-10-12 18:14:25 +0200169113901272
Senthil Kumaran77493202016-06-04 20:07:34 -07001692>>> id(b) # doctest: +SKIP
Georg Brandld8ede4f2013-10-12 18:14:25 +0200169313891296
1694
1695
Georg Brandld7413152009-10-11 21:25:26 +00001696Modules
1697=======
1698
1699How do I create a .pyc file?
1700----------------------------
1701
R David Murrayd913d9d2013-12-13 12:29:29 -05001702When a module is imported for the first time (or when the source file has
1703changed since the current compiled file was created) a ``.pyc`` file containing
1704the compiled code should be created in a ``__pycache__`` subdirectory of the
1705directory containing the ``.py`` file. The ``.pyc`` file will have a
1706filename that starts with the same name as the ``.py`` file, and ends with
1707``.pyc``, with a middle component that depends on the particular ``python``
1708binary that created it. (See :pep:`3147` for details.)
Georg Brandld7413152009-10-11 21:25:26 +00001709
R David Murrayd913d9d2013-12-13 12:29:29 -05001710One reason that a ``.pyc`` file may not be created is a permissions problem
1711with the directory containing the source file, meaning that the ``__pycache__``
1712subdirectory cannot be created. This can happen, for example, if you develop as
1713one user but run as another, such as if you are testing with a web server.
1714
1715Unless the :envvar:`PYTHONDONTWRITEBYTECODE` environment variable is set,
1716creation of a .pyc file is automatic if you're importing a module and Python
1717has the ability (permissions, free space, etc...) to create a ``__pycache__``
1718subdirectory and write the compiled module to that subdirectory.
Georg Brandld7413152009-10-11 21:25:26 +00001719
R David Murrayfdf95032013-06-19 16:58:26 -04001720Running Python on a top level script is not considered an import and no
1721``.pyc`` will be created. For example, if you have a top-level module
R David Murrayd913d9d2013-12-13 12:29:29 -05001722``foo.py`` that imports another module ``xyz.py``, when you run ``foo`` (by
1723typing ``python foo.py`` as a shell command), a ``.pyc`` will be created for
1724``xyz`` because ``xyz`` is imported, but no ``.pyc`` file will be created for
1725``foo`` since ``foo.py`` isn't being imported.
Georg Brandld7413152009-10-11 21:25:26 +00001726
R David Murrayd913d9d2013-12-13 12:29:29 -05001727If you need to create a ``.pyc`` file for ``foo`` -- that is, to create a
1728``.pyc`` file for a module that is not imported -- you can, using the
1729:mod:`py_compile` and :mod:`compileall` modules.
Georg Brandld7413152009-10-11 21:25:26 +00001730
1731The :mod:`py_compile` module can manually compile any module. One way is to use
1732the ``compile()`` function in that module interactively::
1733
1734 >>> import py_compile
R David Murrayfdf95032013-06-19 16:58:26 -04001735 >>> py_compile.compile('foo.py') # doctest: +SKIP
Georg Brandld7413152009-10-11 21:25:26 +00001736
R David Murrayd913d9d2013-12-13 12:29:29 -05001737This will write the ``.pyc`` to a ``__pycache__`` subdirectory in the same
1738location as ``foo.py`` (or you can override that with the optional parameter
1739``cfile``).
Georg Brandld7413152009-10-11 21:25:26 +00001740
1741You can also automatically compile all files in a directory or directories using
1742the :mod:`compileall` module. You can do it from the shell prompt by running
1743``compileall.py`` and providing the path of a directory containing Python files
1744to compile::
1745
1746 python -m compileall .
1747
1748
1749How do I find the current module name?
1750--------------------------------------
1751
1752A module can find out its own module name by looking at the predefined global
1753variable ``__name__``. If this has the value ``'__main__'``, the program is
1754running as a script. Many modules that are usually used by importing them also
1755provide a command-line interface or a self-test, and only execute this code
1756after checking ``__name__``::
1757
1758 def main():
Georg Brandl62eaaf62009-12-19 17:51:41 +00001759 print('Running test...')
Georg Brandld7413152009-10-11 21:25:26 +00001760 ...
1761
1762 if __name__ == '__main__':
1763 main()
1764
1765
1766How can I have modules that mutually import each other?
1767-------------------------------------------------------
1768
1769Suppose you have the following modules:
1770
1771foo.py::
1772
1773 from bar import bar_var
1774 foo_var = 1
1775
1776bar.py::
1777
1778 from foo import foo_var
1779 bar_var = 2
1780
1781The problem is that the interpreter will perform the following steps:
1782
1783* main imports foo
1784* Empty globals for foo are created
1785* foo is compiled and starts executing
1786* foo imports bar
1787* Empty globals for bar are created
1788* bar is compiled and starts executing
1789* bar imports foo (which is a no-op since there already is a module named foo)
1790* bar.foo_var = foo.foo_var
1791
1792The last step fails, because Python isn't done with interpreting ``foo`` yet and
1793the global symbol dictionary for ``foo`` is still empty.
1794
1795The same thing happens when you use ``import foo``, and then try to access
1796``foo.foo_var`` in global code.
1797
1798There are (at least) three possible workarounds for this problem.
1799
1800Guido van Rossum recommends avoiding all uses of ``from <module> import ...``,
1801and placing all code inside functions. Initializations of global variables and
1802class variables should use constants or built-in functions only. This means
1803everything from an imported module is referenced as ``<module>.<name>``.
1804
1805Jim Roskind suggests performing steps in the following order in each module:
1806
1807* exports (globals, functions, and classes that don't need imported base
1808 classes)
1809* ``import`` statements
1810* active code (including globals that are initialized from imported values).
1811
1812van Rossum doesn't like this approach much because the imports appear in a
1813strange place, but it does work.
1814
1815Matthias Urlichs recommends restructuring your code so that the recursive import
1816is not necessary in the first place.
1817
1818These solutions are not mutually exclusive.
1819
1820
1821__import__('x.y.z') returns <module 'x'>; how do I get z?
1822---------------------------------------------------------
1823
Ezio Melottie4aad5a2014-08-04 19:34:29 +03001824Consider using the convenience function :func:`~importlib.import_module` from
1825:mod:`importlib` instead::
Georg Brandld7413152009-10-11 21:25:26 +00001826
Ezio Melottie4aad5a2014-08-04 19:34:29 +03001827 z = importlib.import_module('x.y.z')
Georg Brandld7413152009-10-11 21:25:26 +00001828
1829
1830When I edit an imported module and reimport it, the changes don't show up. Why does this happen?
1831-------------------------------------------------------------------------------------------------
1832
1833For reasons of efficiency as well as consistency, Python only reads the module
1834file on the first time a module is imported. If it didn't, in a program
1835consisting of many modules where each one imports the same basic module, the
Brett Cannon4f422e32013-06-14 22:49:00 -04001836basic module would be parsed and re-parsed many times. To force re-reading of a
Georg Brandld7413152009-10-11 21:25:26 +00001837changed module, do this::
1838
Brett Cannon4f422e32013-06-14 22:49:00 -04001839 import importlib
Georg Brandld7413152009-10-11 21:25:26 +00001840 import modname
Brett Cannon4f422e32013-06-14 22:49:00 -04001841 importlib.reload(modname)
Georg Brandld7413152009-10-11 21:25:26 +00001842
1843Warning: this technique is not 100% fool-proof. In particular, modules
1844containing statements like ::
1845
1846 from modname import some_objects
1847
1848will continue to work with the old version of the imported objects. If the
1849module contains class definitions, existing class instances will *not* be
1850updated to use the new class definition. This can result in the following
1851paradoxical behaviour:
1852
Brett Cannon4f422e32013-06-14 22:49:00 -04001853 >>> import importlib
Georg Brandld7413152009-10-11 21:25:26 +00001854 >>> import cls
1855 >>> c = cls.C() # Create an instance of C
Brett Cannon4f422e32013-06-14 22:49:00 -04001856 >>> importlib.reload(cls)
Georg Brandl62eaaf62009-12-19 17:51:41 +00001857 <module 'cls' from 'cls.py'>
Georg Brandld7413152009-10-11 21:25:26 +00001858 >>> isinstance(c, cls.C) # isinstance is false?!?
1859 False
1860
Georg Brandl62eaaf62009-12-19 17:51:41 +00001861The nature of the problem is made clear if you print out the "identity" of the
1862class objects:
Georg Brandld7413152009-10-11 21:25:26 +00001863
Georg Brandl62eaaf62009-12-19 17:51:41 +00001864 >>> hex(id(c.__class__))
1865 '0x7352a0'
1866 >>> hex(id(cls.C))
1867 '0x4198d0'