~ubuntu-branches/ubuntu/trusty/python3.4/trusty-proposed

« back to all changes in this revision

Viewing changes to Doc/faq/programming.rst

  • Committer: Package Import Robot
  • Author(s): Matthias Klose
  • Date: 2013-11-25 09:44:27 UTC
  • Revision ID: package-import@ubuntu.com-20131125094427-lzxj8ap5w01lmo7f
Tags: upstream-3.4~b1
ImportĀ upstreamĀ versionĀ 3.4~b1

Show diffs side-by-side

added added

removed removed

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