blob: 2dfdb3e6d831279a1378f8b7184a5b091a7e9fd4 [file] [log] [blame]
Georg Brandl6728c5a2009-10-11 18:31:23 +00001:tocdepth: 2
2
3===============
4Programming FAQ
5===============
6
Georg Brandl44ea77b2013-03-28 13:28:44 +01007.. only:: html
8
9 .. contents::
Georg Brandl6728c5a2009-10-11 18:31:23 +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
26graphical debugger. There is documentation for the IDLE debugger at
Georg Brandl06f3b3b2014-10-29 08:36:35 +010027https://www.python.org/idle/doc/idle2.html#Debugger.
Georg Brandl6728c5a2009-10-11 18:31:23 +000028
29PythonWin is a Python IDE that includes a GUI debugger based on pdb. The
30Pythonwin debugger colors breakpoints and has quite a few cool features such as
31debugging non-Pythonwin programs. Pythonwin is available as part of the `Python
32for Windows Extensions <http://sourceforge.net/projects/pywin32/>`__ project and
33as a part of the ActivePython distribution (see
34http://www.activestate.com/Products/ActivePython/index.html).
35
36`Boa Constructor <http://boa-constructor.sourceforge.net/>`_ is an IDE and GUI
37builder that uses wxWidgets. It offers visual frame creation and manipulation,
38an object inspector, many views on the source like object browsers, inheritance
39hierarchies, doc string generated html documentation, an advanced debugger,
40integrated help, and Zope support.
41
42`Eric <http://www.die-offenbachs.de/eric/index.html>`_ is an IDE built on PyQt
43and the Scintilla editing component.
44
45Pydb is a version of the standard Python debugger pdb, modified for use with DDD
46(Data Display Debugger), a popular graphical debugger front end. Pydb can be
47found at http://bashdb.sourceforge.net/pydb/ and DDD can be found at
48http://www.gnu.org/software/ddd.
49
50There are a number of commercial Python IDEs that include graphical debuggers.
51They include:
52
53* Wing IDE (http://wingware.com/)
54* Komodo IDE (http://www.activestate.com/Products/Komodo)
55
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
64http://pychecker.sf.net.
65
66`Pylint <http://www.logilab.org/projects/pylint>`_ is another tool that checks
67if a module satisfies a coding standard, and also makes it possible to write
68plug-ins to add a custom feature. In addition to the bug checking that
69PyChecker performs, Pylint offers some additional features such as checking line
70length, whether variable names are well-formed according to your coding
71standard, whether declared interfaces are fully implemented, and more.
Georg Brandla4314c22009-10-11 20:16:16 +000072http://www.logilab.org/card/pylint_manual provides a full list of Pylint's
73features.
Georg Brandl6728c5a2009-10-11 18:31:23 +000074
75
76How can I create a stand-alone binary from a Python script?
77-----------------------------------------------------------
78
79You don't need the ability to compile Python to C code if all you want is a
80stand-alone program that users can download and run without having to install
81the Python distribution first. There are a number of tools that determine the
82set of modules required by a program and bind these modules together with a
83Python binary to produce a single executable.
84
85One is to use the freeze tool, which is included in the Python source tree as
86``Tools/freeze``. It converts Python byte code to C arrays; a C compiler you can
87embed all your modules into a new program, which is then linked with the
88standard Python modules.
89
90It works by scanning your source recursively for import statements (in both
91forms) and looking for the modules in the standard Python path as well as in the
92source directory (for built-in modules). It then turns the bytecode for modules
93written in Python into C code (array initializers that can be turned into code
94objects using the marshal module) and creates a custom-made config file that
95only contains those built-in modules which are actually used in the program. It
96then compiles the generated C code and links it with the rest of the Python
97interpreter to form a self-contained binary which acts exactly like your script.
98
99Obviously, freeze requires a C compiler. There are several other utilities
100which don't. One is Thomas Heller's py2exe (Windows only) at
101
102 http://www.py2exe.org/
103
104Another is Christian Tismer's `SQFREEZE <http://starship.python.net/crew/pirx>`_
105which appends the byte code to a specially-prepared Python interpreter that can
106find the byte code in the executable.
107
108Other tools include Fredrik Lundh's `Squeeze
109<http://www.pythonware.com/products/python/squeeze>`_ and Anthony Tuininga's
110`cx_Freeze <http://starship.python.net/crew/atuining/cx_Freeze/index.html>`_.
111
112
113Are there coding standards or a style guide for Python programs?
114----------------------------------------------------------------
115
116Yes. The coding style required for standard library modules is documented as
117:pep:`8`.
118
119
120My program is too slow. How do I speed it up?
121---------------------------------------------
122
123That's a tough one, in general. There are many tricks to speed up Python code;
124consider rewriting parts in C as a last resort.
125
126In some cases it's possible to automatically translate Python to C or x86
127assembly language, meaning that you don't have to modify your code to gain
128increased speed.
129
130.. XXX seems to have overlap with other questions!
131
132`Pyrex <http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/>`_ can compile a
133slightly modified version of Python code into a C extension, and can be used on
134many different platforms.
135
136`Psyco <http://psyco.sourceforge.net>`_ is a just-in-time compiler that
137translates Python code into x86 assembly language. If you can use it, Psyco can
138provide dramatic speedups for critical functions.
139
140The rest of this answer will discuss various tricks for squeezing a bit more
141speed out of Python code. *Never* apply any optimization tricks unless you know
142you need them, after profiling has indicated that a particular function is the
143heavily executed hot spot in the code. Optimizations almost always make the
144code less clear, and you shouldn't pay the costs of reduced clarity (increased
145development time, greater likelihood of bugs) unless the resulting performance
146benefit is worth it.
147
148There is a page on the wiki devoted to `performance tips
Georg Brandl06f3b3b2014-10-29 08:36:35 +0100149<https://wiki.python.org/moin/PythonSpeed/PerformanceTips>`_.
Georg Brandl6728c5a2009-10-11 18:31:23 +0000150
151Guido van Rossum has written up an anecdote related to optimization at
Georg Brandl06f3b3b2014-10-29 08:36:35 +0100152https://www.python.org/doc/essays/list2str.
Georg Brandl6728c5a2009-10-11 18:31:23 +0000153
154One thing to notice is that function and (especially) method calls are rather
155expensive; if you have designed a purely OO interface with lots of tiny
156functions that don't do much more than get or set an instance variable or call
157another method, you might consider using a more direct way such as directly
158accessing instance variables. Also see the standard module :mod:`profile` which
159makes it possible to find out where your program is spending most of its time
160(if you have some patience -- the profiling itself can slow your program down by
161an order of magnitude).
162
163Remember that many standard optimization heuristics you may know from other
164programming experience may well apply to Python. For example it may be faster
165to send output to output devices using larger writes rather than smaller ones in
166order to reduce the overhead of kernel system calls. Thus CGI scripts that
167write all output in "one shot" may be faster than those that write lots of small
168pieces of output.
169
170Also, be sure to use Python's core features where appropriate. For example,
171slicing allows programs to chop up lists and other sequence objects in a single
172tick of the interpreter's mainloop using highly optimized C implementations.
173Thus to get the same effect as::
174
175 L2 = []
Georg Brandleacada82011-08-25 11:52:26 +0200176 for i in range(3):
Georg Brandl6728c5a2009-10-11 18:31:23 +0000177 L2.append(L1[i])
178
179it is much shorter and far faster to use ::
180
Georg Brandl0cedb4b2009-12-20 14:20:16 +0000181 L2 = list(L1[:3]) # "list" is redundant if L1 is a list.
Georg Brandl6728c5a2009-10-11 18:31:23 +0000182
Georg Brandl6f82cd32010-02-06 18:44:44 +0000183Note that the functionally-oriented built-in functions such as :func:`map`,
184:func:`zip`, and friends can be a convenient accelerator for loops that
185perform a single task. For example to pair the elements of two lists
186together::
Georg Brandl6728c5a2009-10-11 18:31:23 +0000187
Georg Brandl0cedb4b2009-12-20 14:20:16 +0000188 >>> zip([1, 2, 3], [4, 5, 6])
Georg Brandl6728c5a2009-10-11 18:31:23 +0000189 [(1, 4), (2, 5), (3, 6)]
190
191or to compute a number of sines::
192
Georg Brandl0cedb4b2009-12-20 14:20:16 +0000193 >>> map(math.sin, (1, 2, 3, 4))
194 [0.841470984808, 0.909297426826, 0.14112000806, -0.756802495308]
Georg Brandl6728c5a2009-10-11 18:31:23 +0000195
196The operation completes very quickly in such cases.
197
Georg Brandl0cedb4b2009-12-20 14:20:16 +0000198Other examples include the ``join()`` and ``split()`` :ref:`methods
199of string objects <string-methods>`.
Georg Brandl6728c5a2009-10-11 18:31:23 +0000200For example if s1..s7 are large (10K+) strings then
201``"".join([s1,s2,s3,s4,s5,s6,s7])`` may be far faster than the more obvious
202``s1+s2+s3+s4+s5+s6+s7``, since the "summation" will compute many
203subexpressions, whereas ``join()`` does all the copying in one pass. For
Georg Brandl0cedb4b2009-12-20 14:20:16 +0000204manipulating strings, use the ``replace()`` and the ``format()`` :ref:`methods
205on string objects <string-methods>`. Use regular expressions only when you're
206not dealing with constant string patterns. You may still use :ref:`the old %
207operations <string-formatting>` ``string % tuple`` and ``string % dictionary``.
Georg Brandl6728c5a2009-10-11 18:31:23 +0000208
Georg Brandl6f82cd32010-02-06 18:44:44 +0000209Be sure to use the :meth:`list.sort` built-in method to do sorting, and see the
Georg Brandl06f3b3b2014-10-29 08:36:35 +0100210`sorting mini-HOWTO <https://wiki.python.org/moin/HowTo/Sorting>`_ for examples
Georg Brandl6728c5a2009-10-11 18:31:23 +0000211of moderately advanced usage. :meth:`list.sort` beats other techniques for
212sorting in all but the most extreme circumstances.
213
214Another common trick is to "push loops into functions or methods." For example
215suppose you have a program that runs slowly and you use the profiler to
216determine that a Python function ``ff()`` is being called lots of times. If you
Georg Brandl0cedb4b2009-12-20 14:20:16 +0000217notice that ``ff()``::
Georg Brandl6728c5a2009-10-11 18:31:23 +0000218
219 def ff(x):
220 ... # do something with x computing result...
221 return result
222
223tends to be called in loops like::
224
225 list = map(ff, oldlist)
226
227or::
228
229 for x in sequence:
230 value = ff(x)
231 ... # do something with value...
232
233then you can often eliminate function call overhead by rewriting ``ff()`` to::
234
235 def ffseq(seq):
236 resultseq = []
237 for x in seq:
238 ... # do something with x computing result...
239 resultseq.append(result)
240 return resultseq
241
242and rewrite the two examples to ``list = ffseq(oldlist)`` and to::
243
244 for value in ffseq(sequence):
245 ... # do something with value...
246
247Single calls to ``ff(x)`` translate to ``ffseq([x])[0]`` with little penalty.
248Of course this technique is not always appropriate and there are other variants
249which you can figure out.
250
251You can gain some performance by explicitly storing the results of a function or
252method lookup into a local variable. A loop like::
253
254 for key in token:
255 dict[key] = dict.get(key, 0) + 1
256
257resolves ``dict.get`` every iteration. If the method isn't going to change, a
258slightly faster implementation is::
259
260 dict_get = dict.get # look up the method once
261 for key in token:
262 dict[key] = dict_get(key, 0) + 1
263
264Default arguments can be used to determine values once, at compile time instead
265of at run time. This can only be done for functions or objects which will not
266be changed during program execution, such as replacing ::
267
268 def degree_sin(deg):
269 return math.sin(deg * math.pi / 180.0)
270
271with ::
272
273 def degree_sin(deg, factor=math.pi/180.0, sin=math.sin):
274 return sin(deg * factor)
275
276Because this trick uses default arguments for terms which should not be changed,
277it should only be used when you are not concerned with presenting a possibly
278confusing API to your users.
279
280
281Core Language
282=============
283
R. David Murray89064382009-11-10 18:58:02 +0000284Why am I getting an UnboundLocalError when the variable has a value?
285--------------------------------------------------------------------
Georg Brandl6728c5a2009-10-11 18:31:23 +0000286
R. David Murray89064382009-11-10 18:58:02 +0000287It can be a surprise to get the UnboundLocalError in previously working
288code when it is modified by adding an assignment statement somewhere in
289the body of a function.
Georg Brandl6728c5a2009-10-11 18:31:23 +0000290
R. David Murray89064382009-11-10 18:58:02 +0000291This code:
Georg Brandl6728c5a2009-10-11 18:31:23 +0000292
R. David Murray89064382009-11-10 18:58:02 +0000293 >>> x = 10
294 >>> def bar():
295 ... print x
296 >>> bar()
297 10
Georg Brandl6728c5a2009-10-11 18:31:23 +0000298
R. David Murray89064382009-11-10 18:58:02 +0000299works, but this code:
Georg Brandl6728c5a2009-10-11 18:31:23 +0000300
R. David Murray89064382009-11-10 18:58:02 +0000301 >>> x = 10
302 >>> def foo():
303 ... print x
304 ... x += 1
Georg Brandl6728c5a2009-10-11 18:31:23 +0000305
R. David Murray89064382009-11-10 18:58:02 +0000306results in an UnboundLocalError:
Georg Brandl6728c5a2009-10-11 18:31:23 +0000307
R. David Murray89064382009-11-10 18:58:02 +0000308 >>> foo()
309 Traceback (most recent call last):
310 ...
311 UnboundLocalError: local variable 'x' referenced before assignment
312
313This is because when you make an assignment to a variable in a scope, that
314variable becomes local to that scope and shadows any similarly named variable
315in the outer scope. Since the last statement in foo assigns a new value to
316``x``, the compiler recognizes it as a local variable. Consequently when the
317earlier ``print x`` attempts to print the uninitialized local variable and
318an error results.
319
320In the example above you can access the outer scope variable by declaring it
321global:
322
323 >>> x = 10
324 >>> def foobar():
325 ... global x
326 ... print x
327 ... x += 1
328 >>> foobar()
329 10
330
331This explicit declaration is required in order to remind you that (unlike the
332superficially analogous situation with class and instance variables) you are
333actually modifying the value of the variable in the outer scope:
334
335 >>> print x
336 11
337
Georg Brandl6728c5a2009-10-11 18:31:23 +0000338
339What are the rules for local and global variables in Python?
340------------------------------------------------------------
341
342In Python, variables that are only referenced inside a function are implicitly
343global. If a variable is assigned a new value anywhere within the function's
344body, it's assumed to be a local. If a variable is ever assigned a new value
345inside the function, the variable is implicitly local, and you need to
346explicitly declare it as 'global'.
347
348Though a bit surprising at first, a moment's consideration explains this. On
349one hand, requiring :keyword:`global` for assigned variables provides a bar
350against unintended side-effects. On the other hand, if ``global`` was required
351for all global references, you'd be using ``global`` all the time. You'd have
Georg Brandl6f82cd32010-02-06 18:44:44 +0000352to declare as global every reference to a built-in function or to a component of
Georg Brandl6728c5a2009-10-11 18:31:23 +0000353an imported module. This clutter would defeat the usefulness of the ``global``
354declaration for identifying side-effects.
355
356
Ezio Melotti58abc5b2013-01-05 00:49:48 +0200357Why do lambdas defined in a loop with different values all return the same result?
358----------------------------------------------------------------------------------
359
360Assume you use a for loop to define a few different lambdas (or even plain
361functions), e.g.::
362
R David Murrayff229842013-06-19 17:00:43 -0400363 >>> squares = []
364 >>> for x in range(5):
365 ... squares.append(lambda: x**2)
Ezio Melotti58abc5b2013-01-05 00:49:48 +0200366
367This gives you a list that contains 5 lambdas that calculate ``x**2``. You
368might expect that, when called, they would return, respectively, ``0``, ``1``,
369``4``, ``9``, and ``16``. However, when you actually try you will see that
370they all return ``16``::
371
372 >>> squares[2]()
373 16
374 >>> squares[4]()
375 16
376
377This happens because ``x`` is not local to the lambdas, but is defined in
378the outer scope, and it is accessed when the lambda is called --- not when it
379is defined. At the end of the loop, the value of ``x`` is ``4``, so all the
380functions now return ``4**2``, i.e. ``16``. You can also verify this by
381changing the value of ``x`` and see how the results of the lambdas change::
382
383 >>> x = 8
384 >>> squares[2]()
385 64
386
387In order to avoid this, you need to save the values in variables local to the
388lambdas, so that they don't rely on the value of the global ``x``::
389
R David Murrayff229842013-06-19 17:00:43 -0400390 >>> squares = []
391 >>> for x in range(5):
392 ... squares.append(lambda n=x: n**2)
Ezio Melotti58abc5b2013-01-05 00:49:48 +0200393
394Here, ``n=x`` creates a new variable ``n`` local to the lambda and computed
395when the lambda is defined so that it has the same value that ``x`` had at
396that point in the loop. This means that the value of ``n`` will be ``0``
397in the first lambda, ``1`` in the second, ``2`` in the third, and so on.
398Therefore each lambda will now return the correct result::
399
400 >>> squares[2]()
401 4
402 >>> squares[4]()
403 16
404
405Note that this behaviour is not peculiar to lambdas, but applies to regular
406functions too.
407
408
Georg Brandl6728c5a2009-10-11 18:31:23 +0000409How do I share global variables across modules?
410------------------------------------------------
411
412The canonical way to share information across modules within a single program is
413to create a special module (often called config or cfg). Just import the config
414module in all modules of your application; the module then becomes available as
415a global name. Because there is only one instance of each module, any changes
416made to the module object get reflected everywhere. For example:
417
418config.py::
419
420 x = 0 # Default value of the 'x' configuration setting
421
422mod.py::
423
424 import config
425 config.x = 1
426
427main.py::
428
429 import config
430 import mod
431 print config.x
432
433Note that using a module is also the basis for implementing the Singleton design
434pattern, for the same reason.
435
436
437What are the "best practices" for using import in a module?
438-----------------------------------------------------------
439
440In general, don't use ``from modulename import *``. Doing so clutters the
Georg Brandl8b14dd32014-10-06 16:21:08 +0200441importer's namespace, and makes it much harder for linters to detect undefined
442names.
Georg Brandl6728c5a2009-10-11 18:31:23 +0000443
444Import modules at the top of a file. Doing so makes it clear what other modules
445your code requires and avoids questions of whether the module name is in scope.
446Using one import per line makes it easy to add and delete module imports, but
447using multiple imports per line uses less screen space.
448
449It's good practice if you import modules in the following order:
450
Georg Brandl0cedb4b2009-12-20 14:20:16 +00004511. standard library modules -- e.g. ``sys``, ``os``, ``getopt``, ``re``
Georg Brandl6728c5a2009-10-11 18:31:23 +00004522. third-party library modules (anything installed in Python's site-packages
453 directory) -- e.g. mx.DateTime, ZODB, PIL.Image, etc.
4543. locally-developed modules
455
Georg Brandl8b14dd32014-10-06 16:21:08 +0200456Only use explicit relative package imports. If you're writing code that's in
457the ``package.sub.m1`` module and want to import ``package.sub.m2``, do not just
Georg Brandl6728c5a2009-10-11 18:31:23 +0000458write ``import m2``, even though it's legal. Write ``from package.sub import
Georg Brandl8b14dd32014-10-06 16:21:08 +0200459m2`` or ``from . import m2`` instead.
Georg Brandl6728c5a2009-10-11 18:31:23 +0000460
461It is sometimes necessary to move imports to a function or class to avoid
462problems with circular imports. Gordon McMillan says:
463
464 Circular imports are fine where both modules use the "import <module>" form
465 of import. They fail when the 2nd module wants to grab a name out of the
466 first ("from module import name") and the import is at the top level. That's
467 because names in the 1st are not yet available, because the first module is
468 busy importing the 2nd.
469
470In this case, if the second module is only used in one function, then the import
471can easily be moved into that function. By the time the import is called, the
472first module will have finished initializing, and the second module can do its
473import.
474
475It may also be necessary to move imports out of the top level of code if some of
476the modules are platform-specific. In that case, it may not even be possible to
477import all of the modules at the top of the file. In this case, importing the
478correct modules in the corresponding platform-specific code is a good option.
479
480Only move imports into a local scope, such as inside a function definition, if
481it's necessary to solve a problem such as avoiding a circular import or are
482trying to reduce the initialization time of a module. This technique is
483especially helpful if many of the imports are unnecessary depending on how the
484program executes. You may also want to move imports into a function if the
485modules are only ever used in that function. Note that loading a module the
486first time may be expensive because of the one time initialization of the
487module, but loading a module multiple times is virtually free, costing only a
488couple of dictionary lookups. Even if the module name has gone out of scope,
489the module is probably available in :data:`sys.modules`.
490
Georg Brandl6728c5a2009-10-11 18:31:23 +0000491
Ezio Melotti4f7e09a2014-07-06 20:53:27 +0300492Why are default values shared between objects?
493----------------------------------------------
494
495This type of bug commonly bites neophyte programmers. Consider this function::
496
497 def foo(mydict={}): # Danger: shared reference to one dict for all calls
498 ... compute something ...
499 mydict[key] = value
500 return mydict
501
502The first time you call this function, ``mydict`` contains a single item. The
503second time, ``mydict`` contains two items because when ``foo()`` begins
504executing, ``mydict`` starts out with an item already in it.
505
506It is often expected that a function call creates new objects for default
507values. This is not what happens. Default values are created exactly once, when
508the function is defined. If that object is changed, like the dictionary in this
509example, subsequent calls to the function will refer to this changed object.
510
511By definition, immutable objects such as numbers, strings, tuples, and ``None``,
512are safe from change. Changes to mutable objects such as dictionaries, lists,
513and class instances can lead to confusion.
514
515Because of this feature, it is good programming practice to not use mutable
516objects as default values. Instead, use ``None`` as the default value and
517inside the function, check if the parameter is ``None`` and create a new
518list/dictionary/whatever if it is. For example, don't write::
519
520 def foo(mydict={}):
521 ...
522
523but::
524
525 def foo(mydict=None):
526 if mydict is None:
527 mydict = {} # create a new dict for local namespace
528
529This feature can be useful. When you have a function that's time-consuming to
530compute, a common technique is to cache the parameters and the resulting value
531of each call to the function, and return the cached value if the same value is
532requested again. This is called "memoizing", and can be implemented like this::
533
534 # Callers will never provide a third parameter for this function.
535 def expensive(arg1, arg2, _cache={}):
536 if (arg1, arg2) in _cache:
537 return _cache[(arg1, arg2)]
538
539 # Calculate the value
540 result = ... expensive computation ...
R David Murray276a0a52014-09-29 10:23:43 -0400541 _cache[(arg1, arg2)] = result # Store result in the cache
Ezio Melotti4f7e09a2014-07-06 20:53:27 +0300542 return result
543
544You could use a global variable containing a dictionary instead of the default
545value; it's a matter of taste.
546
547
Georg Brandl6728c5a2009-10-11 18:31:23 +0000548How can I pass optional or keyword parameters from one function to another?
549---------------------------------------------------------------------------
550
551Collect the arguments using the ``*`` and ``**`` specifiers in the function's
552parameter list; this gives you the positional arguments as a tuple and the
553keyword arguments as a dictionary. You can then pass these arguments when
554calling another function by using ``*`` and ``**``::
555
556 def f(x, *args, **kwargs):
557 ...
558 kwargs['width'] = '14.3c'
559 ...
560 g(x, *args, **kwargs)
561
562In the unlikely case that you care about Python versions older than 2.0, use
563:func:`apply`::
564
565 def f(x, *args, **kwargs):
566 ...
567 kwargs['width'] = '14.3c'
568 ...
569 apply(g, (x,)+args, kwargs)
570
571
Chris Jerdonekcf4710c2012-12-25 14:50:21 -0800572.. index::
573 single: argument; difference from parameter
574 single: parameter; difference from argument
575
Chris Jerdonek8da82682012-11-29 19:03:37 -0800576.. _faq-argument-vs-parameter:
577
578What is the difference between arguments and parameters?
579--------------------------------------------------------
580
581:term:`Parameters <parameter>` are defined by the names that appear in a
582function definition, whereas :term:`arguments <argument>` are the values
583actually passed to a function when calling it. Parameters define what types of
584arguments a function can accept. For example, given the function definition::
585
586 def func(foo, bar=None, **kwargs):
587 pass
588
589*foo*, *bar* and *kwargs* are parameters of ``func``. However, when calling
590``func``, for example::
591
592 func(42, bar=314, extra=somevar)
593
594the values ``42``, ``314``, and ``somevar`` are arguments.
595
596
R David Murray276a0a52014-09-29 10:23:43 -0400597Why did changing list 'y' also change list 'x'?
598------------------------------------------------
599
600If you wrote code like::
601
602 >>> x = []
603 >>> y = x
604 >>> y.append(10)
605 >>> y
606 [10]
607 >>> x
608 [10]
609
610you might be wondering why appending an element to ``y`` changed ``x`` too.
611
612There are two factors that produce this result:
613
6141) Variables are simply names that refer to objects. Doing ``y = x`` doesn't
615 create a copy of the list -- it creates a new variable ``y`` that refers to
616 the same object ``x`` refers to. This means that there is only one object
617 (the list), and both ``x`` and ``y`` refer to it.
6182) Lists are :term:`mutable`, which means that you can change their content.
619
620After the call to :meth:`~list.append`, the content of the mutable object has
621changed from ``[]`` to ``[10]``. Since both the variables refer to the same
622object, using either name accesses the modified value ``[10]``.
623
624If we instead assign an immutable object to ``x``::
625
626 >>> x = 5 # ints are immutable
627 >>> y = x
628 >>> x = x + 1 # 5 can't be mutated, we are creating a new object here
629 >>> x
630 6
631 >>> y
632 5
633
634we can see that in this case ``x`` and ``y`` are not equal anymore. This is
635because integers are :term:`immutable`, and when we do ``x = x + 1`` we are not
636mutating the int ``5`` by incrementing its value; instead, we are creating a
637new object (the int ``6``) and assigning it to ``x`` (that is, changing which
638object ``x`` refers to). After this assignment we have two objects (the ints
639``6`` and ``5``) and two variables that refer to them (``x`` now refers to
640``6`` but ``y`` still refers to ``5``).
641
642Some operations (for example ``y.append(10)`` and ``y.sort()``) mutate the
643object, whereas superficially similar operations (for example ``y = y + [10]``
644and ``sorted(y)``) create a new object. In general in Python (and in all cases
645in the standard library) a method that mutates an object will return ``None``
646to help avoid getting the two types of operations confused. So if you
647mistakenly write ``y.sort()`` thinking it will give you a sorted copy of ``y``,
648you'll instead end up with ``None``, which will likely cause your program to
649generate an easily diagnosed error.
650
651However, there is one class of operations where the same operation sometimes
652has different behaviors with different types: the augmented assignment
653operators. For example, ``+=`` mutates lists but not tuples or ints (``a_list
654+= [1, 2, 3]`` is equivalent to ``a_list.extend([1, 2, 3])`` and mutates
655``a_list``, whereas ``some_tuple += (1, 2, 3)`` and ``some_int += 1`` create
656new objects).
657
658In other words:
659
660* If we have a mutable object (:class:`list`, :class:`dict`, :class:`set`,
661 etc.), we can use some specific operations to mutate it and all the variables
662 that refer to it will see the change.
663* If we have an immutable object (:class:`str`, :class:`int`, :class:`tuple`,
664 etc.), all the variables that refer to it will always see the same value,
665 but operations that transform that value into a new value always return a new
666 object.
667
668If you want to know if two variables refer to the same object or not, you can
669use the :keyword:`is` operator, or the built-in function :func:`id`.
670
671
Georg Brandl6728c5a2009-10-11 18:31:23 +0000672How do I write a function with output parameters (call by reference)?
673---------------------------------------------------------------------
674
675Remember that arguments are passed by assignment in Python. Since assignment
676just creates references to objects, there's no alias between an argument name in
677the caller and callee, and so no call-by-reference per se. You can achieve the
678desired effect in a number of ways.
679
6801) By returning a tuple of the results::
681
682 def func2(a, b):
683 a = 'new-value' # a and b are local names
684 b = b + 1 # assigned to new objects
685 return a, b # return new values
686
687 x, y = 'old-value', 99
688 x, y = func2(x, y)
689 print x, y # output: new-value 100
690
691 This is almost always the clearest solution.
692
6932) By using global variables. This isn't thread-safe, and is not recommended.
694
6953) By passing a mutable (changeable in-place) object::
696
697 def func1(a):
698 a[0] = 'new-value' # 'a' references a mutable list
699 a[1] = a[1] + 1 # changes a shared object
700
701 args = ['old-value', 99]
702 func1(args)
703 print args[0], args[1] # output: new-value 100
704
7054) By passing in a dictionary that gets mutated::
706
707 def func3(args):
708 args['a'] = 'new-value' # args is a mutable dictionary
709 args['b'] = args['b'] + 1 # change it in-place
710
711 args = {'a':' old-value', 'b': 99}
712 func3(args)
713 print args['a'], args['b']
714
7155) Or bundle up values in a class instance::
716
717 class callByRef:
718 def __init__(self, **args):
719 for (key, value) in args.items():
720 setattr(self, key, value)
721
722 def func4(args):
723 args.a = 'new-value' # args is a mutable callByRef
724 args.b = args.b + 1 # change object in-place
725
726 args = callByRef(a='old-value', b=99)
727 func4(args)
728 print args.a, args.b
729
730
731 There's almost never a good reason to get this complicated.
732
733Your best choice is to return a tuple containing the multiple results.
734
735
736How do you make a higher order function in Python?
737--------------------------------------------------
738
739You have two choices: you can use nested scopes or you can use callable objects.
740For example, suppose you wanted to define ``linear(a,b)`` which returns a
741function ``f(x)`` that computes the value ``a*x+b``. Using nested scopes::
742
743 def linear(a, b):
744 def result(x):
745 return a * x + b
746 return result
747
748Or using a callable object::
749
750 class linear:
751
752 def __init__(self, a, b):
753 self.a, self.b = a, b
754
755 def __call__(self, x):
756 return self.a * x + self.b
757
758In both cases, ::
759
760 taxes = linear(0.3, 2)
761
762gives a callable object where ``taxes(10e6) == 0.3 * 10e6 + 2``.
763
764The callable object approach has the disadvantage that it is a bit slower and
765results in slightly longer code. However, note that a collection of callables
766can share their signature via inheritance::
767
768 class exponential(linear):
769 # __init__ inherited
770 def __call__(self, x):
771 return self.a * (x ** self.b)
772
773Object can encapsulate state for several methods::
774
775 class counter:
776
777 value = 0
778
779 def set(self, x):
780 self.value = x
781
782 def up(self):
783 self.value = self.value + 1
784
785 def down(self):
786 self.value = self.value - 1
787
788 count = counter()
789 inc, dec, reset = count.up, count.down, count.set
790
791Here ``inc()``, ``dec()`` and ``reset()`` act like functions which share the
792same counting variable.
793
794
795How do I copy an object in Python?
796----------------------------------
797
798In general, try :func:`copy.copy` or :func:`copy.deepcopy` for the general case.
799Not all objects can be copied, but most can.
800
801Some objects can be copied more easily. Dictionaries have a :meth:`~dict.copy`
802method::
803
804 newdict = olddict.copy()
805
806Sequences can be copied by slicing::
807
808 new_l = l[:]
809
810
811How can I find the methods or attributes of an object?
812------------------------------------------------------
813
814For an instance x of a user-defined class, ``dir(x)`` returns an alphabetized
815list of the names containing the instance attributes and methods and attributes
816defined by its class.
817
818
819How can my code discover the name of an object?
820-----------------------------------------------
821
822Generally speaking, it can't, because objects don't really have names.
823Essentially, assignment always binds a name to a value; The same is true of
824``def`` and ``class`` statements, but in that case the value is a
825callable. Consider the following code::
826
827 class A:
828 pass
829
830 B = A
831
832 a = B()
833 b = a
834 print b
Georg Brandl0cedb4b2009-12-20 14:20:16 +0000835 <__main__.A instance at 0x16D07CC>
Georg Brandl6728c5a2009-10-11 18:31:23 +0000836 print a
Georg Brandl0cedb4b2009-12-20 14:20:16 +0000837 <__main__.A instance at 0x16D07CC>
Georg Brandl6728c5a2009-10-11 18:31:23 +0000838
839Arguably the class has a name: even though it is bound to two names and invoked
840through the name B the created instance is still reported as an instance of
841class A. However, it is impossible to say whether the instance's name is a or
842b, since both names are bound to the same value.
843
844Generally speaking it should not be necessary for your code to "know the names"
845of particular values. Unless you are deliberately writing introspective
846programs, this is usually an indication that a change of approach might be
847beneficial.
848
849In comp.lang.python, Fredrik Lundh once gave an excellent analogy in answer to
850this question:
851
852 The same way as you get the name of that cat you found on your porch: the cat
853 (object) itself cannot tell you its name, and it doesn't really care -- so
854 the only way to find out what it's called is to ask all your neighbours
855 (namespaces) if it's their cat (object)...
856
857 ....and don't be surprised if you'll find that it's known by many names, or
858 no name at all!
859
860
861What's up with the comma operator's precedence?
862-----------------------------------------------
863
864Comma is not an operator in Python. Consider this session::
865
866 >>> "a" in "b", "a"
Georg Brandl0cedb4b2009-12-20 14:20:16 +0000867 (False, 'a')
Georg Brandl6728c5a2009-10-11 18:31:23 +0000868
869Since the comma is not an operator, but a separator between expressions the
870above is evaluated as if you had entered::
871
R David Murrayff229842013-06-19 17:00:43 -0400872 ("a" in "b"), "a"
Georg Brandl6728c5a2009-10-11 18:31:23 +0000873
874not::
875
R David Murrayff229842013-06-19 17:00:43 -0400876 "a" in ("b", "a")
Georg Brandl6728c5a2009-10-11 18:31:23 +0000877
878The same is true of the various assignment operators (``=``, ``+=`` etc). They
879are not truly operators but syntactic delimiters in assignment statements.
880
881
882Is there an equivalent of C's "?:" ternary operator?
883----------------------------------------------------
884
885Yes, this feature was added in Python 2.5. The syntax would be as follows::
886
887 [on_true] if [expression] else [on_false]
888
889 x, y = 50, 25
890
891 small = x if x < y else y
892
893For versions previous to 2.5 the answer would be 'No'.
894
Georg Brandl6728c5a2009-10-11 18:31:23 +0000895
896Is it possible to write obfuscated one-liners in Python?
897--------------------------------------------------------
898
899Yes. Usually this is done by nesting :keyword:`lambda` within
900:keyword:`lambda`. See the following three examples, due to Ulf Bartelt::
901
902 # Primes < 1000
903 print filter(None,map(lambda y:y*reduce(lambda x,y:x*y!=0,
904 map(lambda x,y=y:y%x,range(2,int(pow(y,0.5)+1))),1),range(2,1000)))
905
906 # First 10 Fibonacci numbers
Georg Brandl0cedb4b2009-12-20 14:20:16 +0000907 print map(lambda x,f=lambda x,f:(f(x-1,f)+f(x-2,f)) if x>1 else 1: f(x,f),
Georg Brandl6728c5a2009-10-11 18:31:23 +0000908 range(10))
909
910 # Mandelbrot set
911 print (lambda Ru,Ro,Iu,Io,IM,Sx,Sy:reduce(lambda x,y:x+y,map(lambda y,
912 Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,Sy=Sy,L=lambda yc,Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,i=IM,
913 Sx=Sx,Sy=Sy:reduce(lambda x,y:x+y,map(lambda x,xc=Ru,yc=yc,Ru=Ru,Ro=Ro,
914 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
915 >=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(
916 64+F(Ru+x*(Ro-Ru)/Sx,yc,0,0,i)),range(Sx))):L(Iu+y*(Io-Iu)/Sy),range(Sy
917 ))))(-2.1, 0.7, -1.2, 1.2, 30, 80, 24)
918 # \___ ___/ \___ ___/ | | |__ lines on screen
919 # V V | |______ columns on screen
920 # | | |__________ maximum of "iterations"
921 # | |_________________ range on y axis
922 # |____________________________ range on x axis
923
924Don't try this at home, kids!
925
926
927Numbers and strings
928===================
929
930How do I specify hexadecimal and octal integers?
931------------------------------------------------
932
Georg Brandl0cedb4b2009-12-20 14:20:16 +0000933To specify an octal digit, precede the octal value with a zero, and then a lower
934or uppercase "o". For example, to set the variable "a" to the octal value "10"
935(8 in decimal), type::
Georg Brandl6728c5a2009-10-11 18:31:23 +0000936
Georg Brandl0cedb4b2009-12-20 14:20:16 +0000937 >>> a = 0o10
Georg Brandl6728c5a2009-10-11 18:31:23 +0000938 >>> a
939 8
940
941Hexadecimal is just as easy. Simply precede the hexadecimal number with a zero,
942and then a lower or uppercase "x". Hexadecimal digits can be specified in lower
943or uppercase. For example, in the Python interpreter::
944
945 >>> a = 0xa5
946 >>> a
947 165
948 >>> b = 0XB2
949 >>> b
950 178
951
952
Georg Brandl0cedb4b2009-12-20 14:20:16 +0000953Why does -22 // 10 return -3?
954-----------------------------
Georg Brandl6728c5a2009-10-11 18:31:23 +0000955
956It's primarily driven by the desire that ``i % j`` have the same sign as ``j``.
957If you want that, and also want::
958
Georg Brandl0cedb4b2009-12-20 14:20:16 +0000959 i == (i // j) * j + (i % j)
Georg Brandl6728c5a2009-10-11 18:31:23 +0000960
961then integer division has to return the floor. C also requires that identity to
Georg Brandl0cedb4b2009-12-20 14:20:16 +0000962hold, and then compilers that truncate ``i // j`` need to make ``i % j`` have
963the same sign as ``i``.
Georg Brandl6728c5a2009-10-11 18:31:23 +0000964
965There are few real use cases for ``i % j`` when ``j`` is negative. When ``j``
966is positive, there are many, and in virtually all of them it's more useful for
967``i % j`` to be ``>= 0``. If the clock says 10 now, what did it say 200 hours
968ago? ``-190 % 12 == 2`` is useful; ``-190 % 12 == -10`` is a bug waiting to
969bite.
970
Georg Brandl0cedb4b2009-12-20 14:20:16 +0000971.. note::
972
973 On Python 2, ``a / b`` returns the same as ``a // b`` if
974 ``__future__.division`` is not in effect. This is also known as "classic"
975 division.
976
Georg Brandl6728c5a2009-10-11 18:31:23 +0000977
978How do I convert a string to a number?
979--------------------------------------
980
981For integers, use the built-in :func:`int` type constructor, e.g. ``int('144')
982== 144``. Similarly, :func:`float` converts to floating-point,
983e.g. ``float('144') == 144.0``.
984
985By default, these interpret the number as decimal, so that ``int('0144') ==
986144`` and ``int('0x144')`` raises :exc:`ValueError`. ``int(string, base)`` takes
987the base to convert from as a second optional argument, so ``int('0x144', 16) ==
988324``. If the base is specified as 0, the number is interpreted using Python's
989rules: a leading '0' indicates octal, and '0x' indicates a hex number.
990
991Do not use the built-in function :func:`eval` if all you need is to convert
992strings to numbers. :func:`eval` will be significantly slower and it presents a
993security risk: someone could pass you a Python expression that might have
994unwanted side effects. For example, someone could pass
995``__import__('os').system("rm -rf $HOME")`` which would erase your home
996directory.
997
998:func:`eval` also has the effect of interpreting numbers as Python expressions,
999so that e.g. ``eval('09')`` gives a syntax error because Python regards numbers
1000starting with '0' as octal (base 8).
1001
1002
1003How do I convert a number to a string?
1004--------------------------------------
1005
1006To convert, e.g., the number 144 to the string '144', use the built-in type
1007constructor :func:`str`. If you want a hexadecimal or octal representation, use
Georg Brandl0cedb4b2009-12-20 14:20:16 +00001008the built-in functions :func:`hex` or :func:`oct`. For fancy formatting, see
1009the :ref:`formatstrings` section, e.g. ``"{:04d}".format(144)`` yields
1010``'0144'`` and ``"{:.3f}".format(1/3)`` yields ``'0.333'``. You may also use
1011:ref:`the % operator <string-formatting>` on strings. See the library reference
1012manual for details.
Georg Brandl6728c5a2009-10-11 18:31:23 +00001013
1014
1015How do I modify a string in place?
1016----------------------------------
1017
1018You can't, because strings are immutable. If you need an object with this
1019ability, try converting the string to a list or use the array module::
1020
R David Murrayff229842013-06-19 17:00:43 -04001021 >>> import io
Georg Brandl6728c5a2009-10-11 18:31:23 +00001022 >>> s = "Hello, world"
1023 >>> a = list(s)
1024 >>> print a
1025 ['H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd']
1026 >>> a[7:] = list("there!")
1027 >>> ''.join(a)
1028 'Hello, there!'
1029
1030 >>> import array
1031 >>> a = array.array('c', s)
1032 >>> print a
1033 array('c', 'Hello, world')
Serhiy Storchakab7128732013-12-24 11:04:06 +02001034 >>> a[0] = 'y'; print a
R David Murrayff229842013-06-19 17:00:43 -04001035 array('c', 'yello, world')
Georg Brandl6728c5a2009-10-11 18:31:23 +00001036 >>> a.tostring()
1037 'yello, world'
1038
1039
1040How do I use strings to call functions/methods?
1041-----------------------------------------------
1042
1043There are various techniques.
1044
1045* The best is to use a dictionary that maps strings to functions. The primary
1046 advantage of this technique is that the strings do not need to match the names
1047 of the functions. This is also the primary technique used to emulate a case
1048 construct::
1049
1050 def a():
1051 pass
1052
1053 def b():
1054 pass
1055
1056 dispatch = {'go': a, 'stop': b} # Note lack of parens for funcs
1057
1058 dispatch[get_input()]() # Note trailing parens to call function
1059
1060* Use the built-in function :func:`getattr`::
1061
1062 import foo
1063 getattr(foo, 'bar')()
1064
1065 Note that :func:`getattr` works on any object, including classes, class
1066 instances, modules, and so on.
1067
1068 This is used in several places in the standard library, like this::
1069
1070 class Foo:
1071 def do_foo(self):
1072 ...
1073
1074 def do_bar(self):
1075 ...
1076
1077 f = getattr(foo_instance, 'do_' + opname)
1078 f()
1079
1080
1081* Use :func:`locals` or :func:`eval` to resolve the function name::
1082
1083 def myFunc():
1084 print "hello"
1085
1086 fname = "myFunc"
1087
1088 f = locals()[fname]
1089 f()
1090
1091 f = eval(fname)
1092 f()
1093
1094 Note: Using :func:`eval` is slow and dangerous. If you don't have absolute
1095 control over the contents of the string, someone could pass a string that
1096 resulted in an arbitrary function being executed.
1097
1098Is there an equivalent to Perl's chomp() for removing trailing newlines from strings?
1099-------------------------------------------------------------------------------------
1100
1101Starting with Python 2.2, you can use ``S.rstrip("\r\n")`` to remove all
Georg Brandl09302282010-10-06 09:32:48 +00001102occurrences of any line terminator from the end of the string ``S`` without
Georg Brandl6728c5a2009-10-11 18:31:23 +00001103removing other trailing whitespace. If the string ``S`` represents more than
1104one line, with several empty lines at the end, the line terminators for all the
1105blank lines will be removed::
1106
1107 >>> lines = ("line 1 \r\n"
1108 ... "\r\n"
1109 ... "\r\n")
1110 >>> lines.rstrip("\n\r")
Georg Brandl0cedb4b2009-12-20 14:20:16 +00001111 'line 1 '
Georg Brandl6728c5a2009-10-11 18:31:23 +00001112
1113Since this is typically only desired when reading text one line at a time, using
1114``S.rstrip()`` this way works well.
1115
Georg Brandl0cedb4b2009-12-20 14:20:16 +00001116For older versions of Python, there are two partial substitutes:
Georg Brandl6728c5a2009-10-11 18:31:23 +00001117
1118- If you want to remove all trailing whitespace, use the ``rstrip()`` method of
1119 string objects. This removes all trailing whitespace, not just a single
1120 newline.
1121
1122- Otherwise, if there is only one line in the string ``S``, use
1123 ``S.splitlines()[0]``.
1124
1125
1126Is there a scanf() or sscanf() equivalent?
1127------------------------------------------
1128
1129Not as such.
1130
1131For simple input parsing, the easiest approach is usually to split the line into
1132whitespace-delimited words using the :meth:`~str.split` method of string objects
1133and then convert decimal strings to numeric values using :func:`int` or
1134:func:`float`. ``split()`` supports an optional "sep" parameter which is useful
1135if the line uses something other than whitespace as a separator.
1136
Brian Curtine49aefc2010-09-23 13:48:06 +00001137For more complicated input parsing, regular expressions are more powerful
Sandro Tosi98ed08f2012-01-14 16:42:02 +01001138than C's :c:func:`sscanf` and better suited for the task.
Georg Brandl6728c5a2009-10-11 18:31:23 +00001139
1140
1141What does 'UnicodeError: ASCII [decoding,encoding] error: ordinal not in range(128)' mean?
1142------------------------------------------------------------------------------------------
1143
1144This error indicates that your Python installation can handle only 7-bit ASCII
1145strings. There are a couple ways to fix or work around the problem.
1146
1147If your programs must handle data in arbitrary character set encodings, the
1148environment the application runs in will generally identify the encoding of the
1149data it is handing you. You need to convert the input to Unicode data using
1150that encoding. For example, a program that handles email or web input will
1151typically find character set encoding information in Content-Type headers. This
1152can then be used to properly convert input data to Unicode. Assuming the string
1153referred to by ``value`` is encoded as UTF-8::
1154
1155 value = unicode(value, "utf-8")
1156
1157will return a Unicode object. If the data is not correctly encoded as UTF-8,
1158the above call will raise a :exc:`UnicodeError` exception.
1159
1160If you only want strings converted to Unicode which have non-ASCII data, you can
1161try converting them first assuming an ASCII encoding, and then generate Unicode
1162objects if that fails::
1163
1164 try:
1165 x = unicode(value, "ascii")
1166 except UnicodeError:
1167 value = unicode(value, "utf-8")
1168 else:
1169 # value was valid ASCII data
1170 pass
1171
1172It's possible to set a default encoding in a file called ``sitecustomize.py``
1173that's part of the Python library. However, this isn't recommended because
1174changing the Python-wide default encoding may cause third-party extension
1175modules to fail.
1176
1177Note that on Windows, there is an encoding known as "mbcs", which uses an
1178encoding specific to your current locale. In many cases, and particularly when
1179working with COM, this may be an appropriate default encoding to use.
1180
1181
1182Sequences (Tuples/Lists)
1183========================
1184
1185How do I convert between tuples and lists?
1186------------------------------------------
1187
1188The type constructor ``tuple(seq)`` converts any sequence (actually, any
1189iterable) into a tuple with the same items in the same order.
1190
1191For example, ``tuple([1, 2, 3])`` yields ``(1, 2, 3)`` and ``tuple('abc')``
1192yields ``('a', 'b', 'c')``. If the argument is a tuple, it does not make a copy
1193but returns the same object, so it is cheap to call :func:`tuple` when you
1194aren't sure that an object is already a tuple.
1195
1196The type constructor ``list(seq)`` converts any sequence or iterable into a list
1197with the same items in the same order. For example, ``list((1, 2, 3))`` yields
1198``[1, 2, 3]`` and ``list('abc')`` yields ``['a', 'b', 'c']``. If the argument
1199is a list, it makes a copy just like ``seq[:]`` would.
1200
1201
1202What's a negative index?
1203------------------------
1204
1205Python sequences are indexed with positive numbers and negative numbers. For
1206positive numbers 0 is the first index 1 is the second index and so forth. For
1207negative indices -1 is the last index and -2 is the penultimate (next to last)
1208index and so forth. Think of ``seq[-n]`` as the same as ``seq[len(seq)-n]``.
1209
1210Using negative indices can be very convenient. For example ``S[:-1]`` is all of
1211the string except for its last character, which is useful for removing the
1212trailing newline from a string.
1213
1214
1215How do I iterate over a sequence in reverse order?
1216--------------------------------------------------
1217
Georg Brandl6f82cd32010-02-06 18:44:44 +00001218Use the :func:`reversed` built-in function, which is new in Python 2.4::
Georg Brandl6728c5a2009-10-11 18:31:23 +00001219
1220 for x in reversed(sequence):
1221 ... # do something with x...
1222
1223This won't touch your original sequence, but build a new copy with reversed
1224order to iterate over.
1225
1226With Python 2.3, you can use an extended slice syntax::
1227
1228 for x in sequence[::-1]:
1229 ... # do something with x...
1230
1231
1232How do you remove duplicates from a list?
1233-----------------------------------------
1234
1235See the Python Cookbook for a long discussion of many ways to do this:
1236
1237 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52560
1238
1239If you don't mind reordering the list, sort it and then scan from the end of the
1240list, deleting duplicates as you go::
1241
Georg Brandl0cedb4b2009-12-20 14:20:16 +00001242 if mylist:
1243 mylist.sort()
1244 last = mylist[-1]
1245 for i in range(len(mylist)-2, -1, -1):
1246 if last == mylist[i]:
1247 del mylist[i]
Georg Brandl6728c5a2009-10-11 18:31:23 +00001248 else:
Georg Brandl0cedb4b2009-12-20 14:20:16 +00001249 last = mylist[i]
Georg Brandl6728c5a2009-10-11 18:31:23 +00001250
1251If all elements of the list may be used as dictionary keys (i.e. they are all
1252hashable) this is often faster ::
1253
1254 d = {}
Georg Brandl0cedb4b2009-12-20 14:20:16 +00001255 for x in mylist:
1256 d[x] = 1
1257 mylist = list(d.keys())
Georg Brandl6728c5a2009-10-11 18:31:23 +00001258
1259In Python 2.5 and later, the following is possible instead::
1260
Georg Brandl0cedb4b2009-12-20 14:20:16 +00001261 mylist = list(set(mylist))
Georg Brandl6728c5a2009-10-11 18:31:23 +00001262
1263This converts the list into a set, thereby removing duplicates, and then back
1264into a list.
1265
1266
1267How do you make an array in Python?
1268-----------------------------------
1269
1270Use a list::
1271
1272 ["this", 1, "is", "an", "array"]
1273
1274Lists are equivalent to C or Pascal arrays in their time complexity; the primary
1275difference is that a Python list can contain objects of many different types.
1276
1277The ``array`` module also provides methods for creating arrays of fixed types
1278with compact representations, but they are slower to index than lists. Also
1279note that the Numeric extensions and others define array-like structures with
1280various characteristics as well.
1281
1282To get Lisp-style linked lists, you can emulate cons cells using tuples::
1283
1284 lisp_list = ("like", ("this", ("example", None) ) )
1285
1286If mutability is desired, you could use lists instead of tuples. Here the
1287analogue of lisp car is ``lisp_list[0]`` and the analogue of cdr is
1288``lisp_list[1]``. Only do this if you're sure you really need to, because it's
1289usually a lot slower than using Python lists.
1290
1291
1292How do I create a multidimensional list?
1293----------------------------------------
1294
1295You probably tried to make a multidimensional array like this::
1296
R David Murrayff229842013-06-19 17:00:43 -04001297 >>> A = [[None] * 2] * 3
Georg Brandl6728c5a2009-10-11 18:31:23 +00001298
1299This looks correct if you print it::
1300
1301 >>> A
1302 [[None, None], [None, None], [None, None]]
1303
1304But when you assign a value, it shows up in multiple places:
1305
1306 >>> A[0][0] = 5
1307 >>> A
1308 [[5, None], [5, None], [5, None]]
1309
1310The reason is that replicating a list with ``*`` doesn't create copies, it only
1311creates references to the existing objects. The ``*3`` creates a list
1312containing 3 references to the same list of length two. Changes to one row will
1313show in all rows, which is almost certainly not what you want.
1314
1315The suggested approach is to create a list of the desired length first and then
1316fill in each element with a newly created list::
1317
1318 A = [None] * 3
1319 for i in range(3):
1320 A[i] = [None] * 2
1321
1322This generates a list containing 3 different lists of length two. You can also
1323use a list comprehension::
1324
1325 w, h = 2, 3
1326 A = [[None] * w for i in range(h)]
1327
1328Or, you can use an extension that provides a matrix datatype; `Numeric Python
Ezio Melottic49805e2013-06-09 01:04:21 +03001329<http://www.numpy.org/>`_ is the best known.
Georg Brandl6728c5a2009-10-11 18:31:23 +00001330
1331
1332How do I apply a method to a sequence of objects?
1333-------------------------------------------------
1334
1335Use a list comprehension::
1336
Georg Brandl0cedb4b2009-12-20 14:20:16 +00001337 result = [obj.method() for obj in mylist]
Georg Brandl6728c5a2009-10-11 18:31:23 +00001338
1339More generically, you can try the following function::
1340
1341 def method_map(objects, method, arguments):
1342 """method_map([a,b], "meth", (1,2)) gives [a.meth(1,2), b.meth(1,2)]"""
1343 nobjects = len(objects)
1344 methods = map(getattr, objects, [method]*nobjects)
1345 return map(apply, methods, [arguments]*nobjects)
1346
1347
R David Murrayed983ab2013-05-20 10:34:58 -04001348Why does a_tuple[i] += ['item'] raise an exception when the addition works?
1349---------------------------------------------------------------------------
1350
1351This is because of a combination of the fact that augmented assignment
1352operators are *assignment* operators, and the difference between mutable and
1353immutable objects in Python.
1354
1355This discussion applies in general when augmented assignment operators are
1356applied to elements of a tuple that point to mutable objects, but we'll use
1357a ``list`` and ``+=`` as our exemplar.
1358
1359If you wrote::
1360
1361 >>> a_tuple = (1, 2)
1362 >>> a_tuple[0] += 1
1363 Traceback (most recent call last):
1364 ...
1365 TypeError: 'tuple' object does not support item assignment
1366
1367The reason for the exception should be immediately clear: ``1`` is added to the
1368object ``a_tuple[0]`` points to (``1``), producing the result object, ``2``,
1369but when we attempt to assign the result of the computation, ``2``, to element
1370``0`` of the tuple, we get an error because we can't change what an element of
1371a tuple points to.
1372
1373Under the covers, what this augmented assignment statement is doing is
1374approximately this::
1375
R David Murraye6f2e6c2013-05-21 11:46:18 -04001376 >>> result = a_tuple[0] + 1
R David Murrayed983ab2013-05-20 10:34:58 -04001377 >>> a_tuple[0] = result
1378 Traceback (most recent call last):
1379 ...
1380 TypeError: 'tuple' object does not support item assignment
1381
1382It is the assignment part of the operation that produces the error, since a
1383tuple is immutable.
1384
1385When you write something like::
1386
1387 >>> a_tuple = (['foo'], 'bar')
1388 >>> a_tuple[0] += ['item']
1389 Traceback (most recent call last):
1390 ...
1391 TypeError: 'tuple' object does not support item assignment
1392
1393The exception is a bit more surprising, and even more surprising is the fact
1394that even though there was an error, the append worked::
1395
1396 >>> a_tuple[0]
1397 ['foo', 'item']
1398
R David Murraye6f2e6c2013-05-21 11:46:18 -04001399To see why this happens, you need to know that (a) if an object implements an
1400``__iadd__`` magic method, it gets called when the ``+=`` augmented assignment
1401is executed, and its return value is what gets used in the assignment statement;
1402and (b) for lists, ``__iadd__`` is equivalent to calling ``extend`` on the list
1403and returning the list. That's why we say that for lists, ``+=`` is a
1404"shorthand" for ``list.extend``::
R David Murrayed983ab2013-05-20 10:34:58 -04001405
1406 >>> a_list = []
1407 >>> a_list += [1]
1408 >>> a_list
1409 [1]
1410
R David Murraye6f2e6c2013-05-21 11:46:18 -04001411This is equivalent to::
R David Murrayed983ab2013-05-20 10:34:58 -04001412
1413 >>> result = a_list.__iadd__([1])
1414 >>> a_list = result
1415
1416The object pointed to by a_list has been mutated, and the pointer to the
1417mutated object is assigned back to ``a_list``. The end result of the
1418assignment is a no-op, since it is a pointer to the same object that ``a_list``
1419was previously pointing to, but the assignment still happens.
1420
1421Thus, in our tuple example what is happening is equivalent to::
1422
1423 >>> result = a_tuple[0].__iadd__(['item'])
1424 >>> a_tuple[0] = result
1425 Traceback (most recent call last):
1426 ...
1427 TypeError: 'tuple' object does not support item assignment
1428
1429The ``__iadd__`` succeeds, and thus the list is extended, but even though
1430``result`` points to the same object that ``a_tuple[0]`` already points to,
1431that final assignment still results in an error, because tuples are immutable.
1432
1433
Georg Brandl6728c5a2009-10-11 18:31:23 +00001434Dictionaries
1435============
1436
1437How can I get a dictionary to display its keys in a consistent order?
1438---------------------------------------------------------------------
1439
1440You can't. Dictionaries store their keys in an unpredictable order, so the
1441display order of a dictionary's elements will be similarly unpredictable.
1442
1443This can be frustrating if you want to save a printable version to a file, make
1444some changes and then compare it with some other printed dictionary. In this
1445case, use the ``pprint`` module to pretty-print the dictionary; the items will
1446be presented in order sorted by the key.
1447
Georg Brandl0cedb4b2009-12-20 14:20:16 +00001448A more complicated solution is to subclass ``dict`` to create a
Georg Brandl6728c5a2009-10-11 18:31:23 +00001449``SortedDict`` class that prints itself in a predictable order. Here's one
1450simpleminded implementation of such a class::
1451
Georg Brandl0cedb4b2009-12-20 14:20:16 +00001452 class SortedDict(dict):
Georg Brandl6728c5a2009-10-11 18:31:23 +00001453 def __repr__(self):
Georg Brandl0cedb4b2009-12-20 14:20:16 +00001454 keys = sorted(self.keys())
1455 result = ("{!r}: {!r}".format(k, self[k]) for k in keys)
1456 return "{{{}}}".format(", ".join(result))
Georg Brandl6728c5a2009-10-11 18:31:23 +00001457
Georg Brandl0cedb4b2009-12-20 14:20:16 +00001458 __str__ = __repr__
Georg Brandl6728c5a2009-10-11 18:31:23 +00001459
1460This will work for many common situations you might encounter, though it's far
1461from a perfect solution. The largest flaw is that if some values in the
1462dictionary are also dictionaries, their values won't be presented in any
1463particular order.
1464
1465
1466I want to do a complicated sort: can you do a Schwartzian Transform in Python?
1467------------------------------------------------------------------------------
1468
1469The technique, attributed to Randal Schwartz of the Perl community, sorts the
1470elements of a list by a metric which maps each element to its "sort value". In
1471Python, just use the ``key`` argument for the ``sort()`` method::
1472
1473 Isorted = L[:]
1474 Isorted.sort(key=lambda s: int(s[10:15]))
1475
1476The ``key`` argument is new in Python 2.4, for older versions this kind of
1477sorting is quite simple to do with list comprehensions. To sort a list of
1478strings by their uppercase values::
1479
Georg Brandl0cedb4b2009-12-20 14:20:16 +00001480 tmp1 = [(x.upper(), x) for x in L] # Schwartzian transform
Georg Brandl6728c5a2009-10-11 18:31:23 +00001481 tmp1.sort()
1482 Usorted = [x[1] for x in tmp1]
1483
1484To sort by the integer value of a subfield extending from positions 10-15 in
1485each string::
1486
Georg Brandl0cedb4b2009-12-20 14:20:16 +00001487 tmp2 = [(int(s[10:15]), s) for s in L] # Schwartzian transform
Georg Brandl6728c5a2009-10-11 18:31:23 +00001488 tmp2.sort()
1489 Isorted = [x[1] for x in tmp2]
1490
1491Note that Isorted may also be computed by ::
1492
1493 def intfield(s):
1494 return int(s[10:15])
1495
1496 def Icmp(s1, s2):
1497 return cmp(intfield(s1), intfield(s2))
1498
1499 Isorted = L[:]
1500 Isorted.sort(Icmp)
1501
1502but since this method calls ``intfield()`` many times for each element of L, it
1503is slower than the Schwartzian Transform.
1504
1505
1506How can I sort one list by values from another list?
1507----------------------------------------------------
1508
1509Merge them into a single list of tuples, sort the resulting list, and then pick
1510out the element you want. ::
1511
1512 >>> list1 = ["what", "I'm", "sorting", "by"]
1513 >>> list2 = ["something", "else", "to", "sort"]
1514 >>> pairs = zip(list1, list2)
1515 >>> pairs
1516 [('what', 'something'), ("I'm", 'else'), ('sorting', 'to'), ('by', 'sort')]
1517 >>> pairs.sort()
1518 >>> result = [ x[1] for x in pairs ]
1519 >>> result
1520 ['else', 'sort', 'to', 'something']
1521
1522An alternative for the last step is::
1523
Georg Brandl0cedb4b2009-12-20 14:20:16 +00001524 >>> result = []
1525 >>> for p in pairs: result.append(p[1])
Georg Brandl6728c5a2009-10-11 18:31:23 +00001526
1527If you find this more legible, you might prefer to use this instead of the final
1528list comprehension. However, it is almost twice as slow for long lists. Why?
1529First, the ``append()`` operation has to reallocate memory, and while it uses
1530some tricks to avoid doing that each time, it still has to do it occasionally,
1531and that costs quite a bit. Second, the expression "result.append" requires an
1532extra attribute lookup, and third, there's a speed reduction from having to make
1533all those function calls.
1534
1535
1536Objects
1537=======
1538
1539What is a class?
1540----------------
1541
1542A class is the particular object type created by executing a class statement.
1543Class objects are used as templates to create instance objects, which embody
1544both the data (attributes) and code (methods) specific to a datatype.
1545
1546A class can be based on one or more other classes, called its base class(es). It
1547then inherits the attributes and methods of its base classes. This allows an
1548object model to be successively refined by inheritance. You might have a
1549generic ``Mailbox`` class that provides basic accessor methods for a mailbox,
1550and subclasses such as ``MboxMailbox``, ``MaildirMailbox``, ``OutlookMailbox``
1551that handle various specific mailbox formats.
1552
1553
1554What is a method?
1555-----------------
1556
1557A method is a function on some object ``x`` that you normally call as
1558``x.name(arguments...)``. Methods are defined as functions inside the class
1559definition::
1560
1561 class C:
1562 def meth (self, arg):
1563 return arg * 2 + self.attribute
1564
1565
1566What is self?
1567-------------
1568
1569Self is merely a conventional name for the first argument of a method. A method
1570defined as ``meth(self, a, b, c)`` should be called as ``x.meth(a, b, c)`` for
1571some instance ``x`` of the class in which the definition occurs; the called
1572method will think it is called as ``meth(x, a, b, c)``.
1573
1574See also :ref:`why-self`.
1575
1576
1577How do I check if an object is an instance of a given class or of a subclass of it?
1578-----------------------------------------------------------------------------------
1579
1580Use the built-in function ``isinstance(obj, cls)``. You can check if an object
1581is an instance of any of a number of classes by providing a tuple instead of a
1582single class, e.g. ``isinstance(obj, (class1, class2, ...))``, and can also
1583check whether an object is one of Python's built-in types, e.g.
1584``isinstance(obj, str)`` or ``isinstance(obj, (int, long, float, complex))``.
1585
1586Note that most programs do not use :func:`isinstance` on user-defined classes
1587very often. If you are developing the classes yourself, a more proper
1588object-oriented style is to define methods on the classes that encapsulate a
1589particular behaviour, instead of checking the object's class and doing a
1590different thing based on what class it is. For example, if you have a function
1591that does something::
1592
Georg Brandl0cedb4b2009-12-20 14:20:16 +00001593 def search(obj):
Georg Brandl6728c5a2009-10-11 18:31:23 +00001594 if isinstance(obj, Mailbox):
1595 # ... code to search a mailbox
1596 elif isinstance(obj, Document):
1597 # ... code to search a document
1598 elif ...
1599
1600A better approach is to define a ``search()`` method on all the classes and just
1601call it::
1602
1603 class Mailbox:
1604 def search(self):
1605 # ... code to search a mailbox
1606
1607 class Document:
1608 def search(self):
1609 # ... code to search a document
1610
1611 obj.search()
1612
1613
1614What is delegation?
1615-------------------
1616
1617Delegation is an object oriented technique (also called a design pattern).
1618Let's say you have an object ``x`` and want to change the behaviour of just one
1619of its methods. You can create a new class that provides a new implementation
1620of the method you're interested in changing and delegates all other methods to
1621the corresponding method of ``x``.
1622
1623Python programmers can easily implement delegation. For example, the following
1624class implements a class that behaves like a file but converts all written data
1625to uppercase::
1626
1627 class UpperOut:
1628
1629 def __init__(self, outfile):
1630 self._outfile = outfile
1631
1632 def write(self, s):
1633 self._outfile.write(s.upper())
1634
1635 def __getattr__(self, name):
1636 return getattr(self._outfile, name)
1637
1638Here the ``UpperOut`` class redefines the ``write()`` method to convert the
1639argument string to uppercase before calling the underlying
1640``self.__outfile.write()`` method. All other methods are delegated to the
1641underlying ``self.__outfile`` object. The delegation is accomplished via the
1642``__getattr__`` method; consult :ref:`the language reference <attribute-access>`
1643for more information about controlling attribute access.
1644
1645Note that for more general cases delegation can get trickier. When attributes
1646must be set as well as retrieved, the class must define a :meth:`__setattr__`
1647method too, and it must do so carefully. The basic implementation of
1648:meth:`__setattr__` is roughly equivalent to the following::
1649
1650 class X:
1651 ...
1652 def __setattr__(self, name, value):
1653 self.__dict__[name] = value
1654 ...
1655
1656Most :meth:`__setattr__` implementations must modify ``self.__dict__`` to store
1657local state for self without causing an infinite recursion.
1658
1659
1660How do I call a method defined in a base class from a derived class that overrides it?
1661--------------------------------------------------------------------------------------
1662
1663If you're using new-style classes, use the built-in :func:`super` function::
1664
1665 class Derived(Base):
1666 def meth (self):
1667 super(Derived, self).meth()
1668
1669If you're using classic classes: For a class definition such as ``class
1670Derived(Base): ...`` you can call method ``meth()`` defined in ``Base`` (or one
1671of ``Base``'s base classes) as ``Base.meth(self, arguments...)``. Here,
1672``Base.meth`` is an unbound method, so you need to provide the ``self``
1673argument.
1674
1675
1676How can I organize my code to make it easier to change the base class?
1677----------------------------------------------------------------------
1678
1679You could define an alias for the base class, assign the real base class to it
1680before your class definition, and use the alias throughout your class. Then all
1681you have to change is the value assigned to the alias. Incidentally, this trick
1682is also handy if you want to decide dynamically (e.g. depending on availability
1683of resources) which base class to use. Example::
1684
1685 BaseAlias = <real base class>
1686
1687 class Derived(BaseAlias):
1688 def meth(self):
1689 BaseAlias.meth(self)
1690 ...
1691
1692
1693How do I create static class data and static class methods?
1694-----------------------------------------------------------
1695
Georg Brandl0cedb4b2009-12-20 14:20:16 +00001696Both static data and static methods (in the sense of C++ or Java) are supported
1697in Python.
Georg Brandl6728c5a2009-10-11 18:31:23 +00001698
1699For static data, simply define a class attribute. To assign a new value to the
1700attribute, you have to explicitly use the class name in the assignment::
1701
1702 class C:
1703 count = 0 # number of times C.__init__ called
1704
1705 def __init__(self):
1706 C.count = C.count + 1
1707
1708 def getcount(self):
1709 return C.count # or return self.count
1710
1711``c.count`` also refers to ``C.count`` for any ``c`` such that ``isinstance(c,
1712C)`` holds, unless overridden by ``c`` itself or by some class on the base-class
1713search path from ``c.__class__`` back to ``C``.
1714
1715Caution: within a method of C, an assignment like ``self.count = 42`` creates a
Georg Brandl0cedb4b2009-12-20 14:20:16 +00001716new and unrelated instance named "count" in ``self``'s own dict. Rebinding of a
1717class-static data name must always specify the class whether inside a method or
1718not::
Georg Brandl6728c5a2009-10-11 18:31:23 +00001719
1720 C.count = 314
1721
1722Static methods are possible since Python 2.2::
1723
1724 class C:
1725 def static(arg1, arg2, arg3):
1726 # No 'self' parameter!
1727 ...
1728 static = staticmethod(static)
1729
1730With Python 2.4's decorators, this can also be written as ::
1731
1732 class C:
1733 @staticmethod
1734 def static(arg1, arg2, arg3):
1735 # No 'self' parameter!
1736 ...
1737
1738However, a far more straightforward way to get the effect of a static method is
1739via a simple module-level function::
1740
1741 def getcount():
1742 return C.count
1743
1744If your code is structured so as to define one class (or tightly related class
1745hierarchy) per module, this supplies the desired encapsulation.
1746
1747
1748How can I overload constructors (or methods) in Python?
1749-------------------------------------------------------
1750
1751This answer actually applies to all methods, but the question usually comes up
1752first in the context of constructors.
1753
1754In C++ you'd write
1755
1756.. code-block:: c
1757
1758 class C {
1759 C() { cout << "No arguments\n"; }
1760 C(int i) { cout << "Argument is " << i << "\n"; }
1761 }
1762
1763In Python you have to write a single constructor that catches all cases using
1764default arguments. For example::
1765
1766 class C:
1767 def __init__(self, i=None):
1768 if i is None:
1769 print "No arguments"
1770 else:
1771 print "Argument is", i
1772
1773This is not entirely equivalent, but close enough in practice.
1774
1775You could also try a variable-length argument list, e.g. ::
1776
1777 def __init__(self, *args):
1778 ...
1779
1780The same approach works for all method definitions.
1781
1782
1783I try to use __spam and I get an error about _SomeClassName__spam.
1784------------------------------------------------------------------
1785
1786Variable names with double leading underscores are "mangled" to provide a simple
1787but effective way to define class private variables. Any identifier of the form
1788``__spam`` (at least two leading underscores, at most one trailing underscore)
1789is textually replaced with ``_classname__spam``, where ``classname`` is the
1790current class name with any leading underscores stripped.
1791
1792This doesn't guarantee privacy: an outside user can still deliberately access
1793the "_classname__spam" attribute, and private values are visible in the object's
1794``__dict__``. Many Python programmers never bother to use private variable
1795names at all.
1796
1797
1798My class defines __del__ but it is not called when I delete the object.
1799-----------------------------------------------------------------------
1800
1801There are several possible reasons for this.
1802
1803The del statement does not necessarily call :meth:`__del__` -- it simply
1804decrements the object's reference count, and if this reaches zero
1805:meth:`__del__` is called.
1806
1807If your data structures contain circular links (e.g. a tree where each child has
1808a parent reference and each parent has a list of children) the reference counts
1809will never go back to zero. Once in a while Python runs an algorithm to detect
1810such cycles, but the garbage collector might run some time after the last
1811reference to your data structure vanishes, so your :meth:`__del__` method may be
1812called at an inconvenient and random time. This is inconvenient if you're trying
1813to reproduce a problem. Worse, the order in which object's :meth:`__del__`
1814methods are executed is arbitrary. You can run :func:`gc.collect` to force a
1815collection, but there *are* pathological cases where objects will never be
1816collected.
1817
1818Despite the cycle collector, it's still a good idea to define an explicit
1819``close()`` method on objects to be called whenever you're done with them. The
1820``close()`` method can then remove attributes that refer to subobjecs. Don't
1821call :meth:`__del__` directly -- :meth:`__del__` should call ``close()`` and
1822``close()`` should make sure that it can be called more than once for the same
1823object.
1824
1825Another way to avoid cyclical references is to use the :mod:`weakref` module,
1826which allows you to point to objects without incrementing their reference count.
1827Tree data structures, for instance, should use weak references for their parent
1828and sibling references (if they need them!).
1829
1830If the object has ever been a local variable in a function that caught an
1831expression in an except clause, chances are that a reference to the object still
1832exists in that function's stack frame as contained in the stack trace.
1833Normally, calling :func:`sys.exc_clear` will take care of this by clearing the
1834last recorded exception.
1835
1836Finally, if your :meth:`__del__` method raises an exception, a warning message
1837is printed to :data:`sys.stderr`.
1838
1839
1840How do I get a list of all instances of a given class?
1841------------------------------------------------------
1842
1843Python does not keep track of all instances of a class (or of a built-in type).
1844You can program the class's constructor to keep track of all instances by
1845keeping a list of weak references to each instance.
1846
1847
Georg Brandl0f79cac2013-10-12 18:14:25 +02001848Why does the result of ``id()`` appear to be not unique?
1849--------------------------------------------------------
1850
1851The :func:`id` builtin returns an integer that is guaranteed to be unique during
1852the lifetime of the object. Since in CPython, this is the object's memory
1853address, it happens frequently that after an object is deleted from memory, the
1854next freshly created object is allocated at the same position in memory. This
1855is illustrated by this example:
1856
1857>>> id(1000)
185813901272
1859>>> id(2000)
186013901272
1861
1862The two ids belong to different integer objects that are created before, and
1863deleted immediately after execution of the ``id()`` call. To be sure that
1864objects whose id you want to examine are still alive, create another reference
1865to the object:
1866
1867>>> a = 1000; b = 2000
1868>>> id(a)
186913901272
1870>>> id(b)
187113891296
1872
1873
Georg Brandl6728c5a2009-10-11 18:31:23 +00001874Modules
1875=======
1876
1877How do I create a .pyc file?
1878----------------------------
1879
1880When a module is imported for the first time (or when the source is more recent
1881than the current compiled file) a ``.pyc`` file containing the compiled code
1882should be created in the same directory as the ``.py`` file.
1883
1884One reason that a ``.pyc`` file may not be created is permissions problems with
1885the directory. This can happen, for example, if you develop as one user but run
1886as another, such as if you are testing with a web server. Creation of a .pyc
1887file is automatic if you're importing a module and Python has the ability
1888(permissions, free space, etc...) to write the compiled module back to the
1889directory.
1890
R David Murrayff229842013-06-19 17:00:43 -04001891Running Python on a top level script is not considered an import and no
1892``.pyc`` will be created. For example, if you have a top-level module
1893``foo.py`` that imports another module ``xyz.py``, when you run ``foo``,
1894``xyz.pyc`` will be created since ``xyz`` is imported, but no ``foo.pyc`` file
1895will be created since ``foo.py`` isn't being imported.
Georg Brandl6728c5a2009-10-11 18:31:23 +00001896
R David Murrayff229842013-06-19 17:00:43 -04001897If you need to create ``foo.pyc`` -- that is, to create a ``.pyc`` file for a module
Georg Brandl6728c5a2009-10-11 18:31:23 +00001898that is not imported -- you can, using the :mod:`py_compile` and
1899:mod:`compileall` modules.
1900
1901The :mod:`py_compile` module can manually compile any module. One way is to use
1902the ``compile()`` function in that module interactively::
1903
1904 >>> import py_compile
R David Murrayff229842013-06-19 17:00:43 -04001905 >>> py_compile.compile('foo.py') # doctest: +SKIP
Georg Brandl6728c5a2009-10-11 18:31:23 +00001906
R David Murrayff229842013-06-19 17:00:43 -04001907This will write the ``.pyc`` to the same location as ``foo.py`` (or you can
Georg Brandl6728c5a2009-10-11 18:31:23 +00001908override that with the optional parameter ``cfile``).
1909
1910You can also automatically compile all files in a directory or directories using
1911the :mod:`compileall` module. You can do it from the shell prompt by running
1912``compileall.py`` and providing the path of a directory containing Python files
1913to compile::
1914
1915 python -m compileall .
1916
1917
1918How do I find the current module name?
1919--------------------------------------
1920
1921A module can find out its own module name by looking at the predefined global
1922variable ``__name__``. If this has the value ``'__main__'``, the program is
1923running as a script. Many modules that are usually used by importing them also
1924provide a command-line interface or a self-test, and only execute this code
1925after checking ``__name__``::
1926
1927 def main():
1928 print 'Running test...'
1929 ...
1930
1931 if __name__ == '__main__':
1932 main()
1933
1934
1935How can I have modules that mutually import each other?
1936-------------------------------------------------------
1937
1938Suppose you have the following modules:
1939
1940foo.py::
1941
1942 from bar import bar_var
1943 foo_var = 1
1944
1945bar.py::
1946
1947 from foo import foo_var
1948 bar_var = 2
1949
1950The problem is that the interpreter will perform the following steps:
1951
1952* main imports foo
1953* Empty globals for foo are created
1954* foo is compiled and starts executing
1955* foo imports bar
1956* Empty globals for bar are created
1957* bar is compiled and starts executing
1958* bar imports foo (which is a no-op since there already is a module named foo)
1959* bar.foo_var = foo.foo_var
1960
1961The last step fails, because Python isn't done with interpreting ``foo`` yet and
1962the global symbol dictionary for ``foo`` is still empty.
1963
1964The same thing happens when you use ``import foo``, and then try to access
1965``foo.foo_var`` in global code.
1966
1967There are (at least) three possible workarounds for this problem.
1968
1969Guido van Rossum recommends avoiding all uses of ``from <module> import ...``,
1970and placing all code inside functions. Initializations of global variables and
1971class variables should use constants or built-in functions only. This means
1972everything from an imported module is referenced as ``<module>.<name>``.
1973
1974Jim Roskind suggests performing steps in the following order in each module:
1975
1976* exports (globals, functions, and classes that don't need imported base
1977 classes)
1978* ``import`` statements
1979* active code (including globals that are initialized from imported values).
1980
1981van Rossum doesn't like this approach much because the imports appear in a
1982strange place, but it does work.
1983
1984Matthias Urlichs recommends restructuring your code so that the recursive import
1985is not necessary in the first place.
1986
1987These solutions are not mutually exclusive.
1988
1989
1990__import__('x.y.z') returns <module 'x'>; how do I get z?
1991---------------------------------------------------------
1992
Ezio Melottic468aba2014-08-04 19:34:29 +03001993Consider using the convenience function :func:`~importlib.import_module` from
1994:mod:`importlib` instead::
Georg Brandl6728c5a2009-10-11 18:31:23 +00001995
Ezio Melottic468aba2014-08-04 19:34:29 +03001996 z = importlib.import_module('x.y.z')
Georg Brandl6728c5a2009-10-11 18:31:23 +00001997
1998
1999When I edit an imported module and reimport it, the changes don't show up. Why does this happen?
2000-------------------------------------------------------------------------------------------------
2001
2002For reasons of efficiency as well as consistency, Python only reads the module
2003file on the first time a module is imported. If it didn't, in a program
2004consisting of many modules where each one imports the same basic module, the
2005basic module would be parsed and re-parsed many times. To force rereading of a
2006changed module, do this::
2007
2008 import modname
2009 reload(modname)
2010
2011Warning: this technique is not 100% fool-proof. In particular, modules
2012containing statements like ::
2013
2014 from modname import some_objects
2015
2016will continue to work with the old version of the imported objects. If the
2017module contains class definitions, existing class instances will *not* be
2018updated to use the new class definition. This can result in the following
2019paradoxical behaviour:
2020
2021 >>> import cls
2022 >>> c = cls.C() # Create an instance of C
2023 >>> reload(cls)
2024 <module 'cls' from 'cls.pyc'>
2025 >>> isinstance(c, cls.C) # isinstance is false?!?
2026 False
2027
2028The nature of the problem is made clear if you print out the class objects:
2029
2030 >>> c.__class__
2031 <class cls.C at 0x7352a0>
2032 >>> cls.C
2033 <class cls.C at 0x4198d0>
2034