Debian Codegraph @

Doc/faq/programming.rst

raw
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 Several debuggers for Python are described below, and the built-in function
20 :func:`breakpoint` allows you to drop into any of them.
21
22 The pdb module is a simple but adequate console-mode debugger for Python. It is
23 part of the standard Python library, and is :mod:`documented in the Library
24 Reference Manual <pdb>`. You can also write your own debugger by using the code
25 for pdb as an example.
26
27 The IDLE interactive development environment, which is part of the standard
28 Python distribution (normally available as
29 `Tools/scripts/idle3 <https://github.com/python/cpython/blob/main/Tools/scripts/idle3>`_),
30 includes a graphical debugger.
31
32 PythonWin is a Python IDE that includes a GUI debugger based on pdb. The
33 PythonWin debugger colors breakpoints and has quite a few cool features such as
34 debugging non-PythonWin programs. PythonWin is available as part of
35 `pywin32 <https://github.com/mhammond/pywin32>`_ project and
36 as a part of the
37 `ActivePython <https://www.activestate.com/products/python/>`_ distribution.
38
39 `Eric <https://eric-ide.python-projects.org/>`_ is an IDE built on PyQt
40 and the Scintilla editing component.
41
42 `trepan3k <https://github.com/rocky/python3-trepan/>`_ is a gdb-like debugger.
43
44 `Visual Studio Code <https://code.visualstudio.com/>`_ is an IDE with debugging
45 tools that integrates with version-control software.
46
47 There are a number of commercial Python IDEs that include graphical debuggers.
48 They include:
49
50 * `Wing IDE <https://wingware.com/>`_
51 * `Komodo IDE <https://www.activestate.com/products/komodo-ide/>`_
52 * `PyCharm <https://www.jetbrains.com/pycharm/>`_
53
54
55 Are there tools to help find bugs or perform static analysis?
56 -------------------------------------------------------------
57
58 Yes.
59
60 `Pylint <https://pylint.pycqa.org/en/latest/index.html>`_ and
61 `Pyflakes <https://github.com/PyCQA/pyflakes>`_ do basic checking that will
62 help you catch bugs sooner.
63
64 Static type checkers such as `Mypy <https://mypy-lang.org/>`_,
65 `Pyre <https://pyre-check.org/>`_, and
66 `Pytype <https://github.com/google/pytype>`_ can check type hints in Python
67 source code.
68
69
70 .. _faq-create-standalone-binary:
71
72 How can I create a stand-alone binary from a Python script?
73 -----------------------------------------------------------
74
75 You don't need the ability to compile Python to C code if all you want is a
76 stand-alone program that users can download and run without having to install
77 the Python distribution first. There are a number of tools that determine the
78 set of modules required by a program and bind these modules together with a
79 Python binary to produce a single executable.
80
81 One is to use the freeze tool, which is included in the Python source tree as
82 `Tools/freeze <https://github.com/python/cpython/tree/main/Tools/freeze>`_.
83 It converts Python byte code to C arrays; with a C compiler you can
84 embed all your modules into a new program, which is then linked with the
85 standard Python modules.
86
87 It works by scanning your source recursively for import statements (in both
88 forms) and looking for the modules in the standard Python path as well as in the
89 source directory (for built-in modules). It then turns the bytecode for modules
90 written in Python into C code (array initializers that can be turned into code
91 objects using the marshal module) and creates a custom-made config file that
92 only contains those built-in modules which are actually used in the program. It
93 then compiles the generated C code and links it with the rest of the Python
94 interpreter to form a self-contained binary which acts exactly like your script.
95
96 The following packages can help with the creation of console and GUI
97 executables:
98
99 * `Nuitka <https://nuitka.net/>`_ (Cross-platform)
100 * `PyInstaller <https://pyinstaller.org/>`_ (Cross-platform)
101 * `PyOxidizer <https://pyoxidizer.readthedocs.io/en/stable/>`_ (Cross-platform)
102 * `cx_Freeze <https://marcelotduarte.github.io/cx_Freeze/>`_ (Cross-platform)
103 * `py2app <https://github.com/ronaldoussoren/py2app>`_ (macOS only)
104 * `py2exe <https://www.py2exe.org/>`_ (Windows only)
105
106 Are there coding standards or a style guide for Python programs?
107 ----------------------------------------------------------------
108
109 Yes. The coding style required for standard library modules is documented as
110 :pep:`8`.
111
112
113 Core Language
114 =============
115
116 .. _faq-unboundlocalerror:
117
118 Why am I getting an UnboundLocalError when the variable has a value?
119 --------------------------------------------------------------------
120
121 It can be a surprise to get the :exc:`UnboundLocalError` in previously working
122 code when it is modified by adding an assignment statement somewhere in
123 the body of a function.
124
125 This code:
126
127 >>> x = 10
128 >>> def bar():
129 ... print(x)
130 ...
131 >>> bar()
132 10
133
134 works, but this code:
135
136 >>> x = 10
137 >>> def foo():
138 ... print(x)
139 ... x += 1
140
141 results in an :exc:`!UnboundLocalError`:
142
143 >>> foo()
144 Traceback (most recent call last):
145 ...
146 UnboundLocalError: local variable 'x' referenced before assignment
147
148 This is because when you make an assignment to a variable in a scope, that
149 variable becomes local to that scope and shadows any similarly named variable
150 in the outer scope. Since the last statement in foo assigns a new value to
151 ``x``, the compiler recognizes it as a local variable. Consequently when the
152 earlier ``print(x)`` attempts to print the uninitialized local variable and
153 an error results.
154
155 In the example above you can access the outer scope variable by declaring it
156 global:
157
158 >>> x = 10
159 >>> def foobar():
160 ... global x
161 ... print(x)
162 ... x += 1
163 ...
164 >>> foobar()
165 10
166
167 This explicit declaration is required in order to remind you that (unlike the
168 superficially analogous situation with class and instance variables) you are
169 actually modifying the value of the variable in the outer scope:
170
171 >>> print(x)
172 11
173
174 You can do a similar thing in a nested scope using the :keyword:`nonlocal`
175 keyword:
176
177 >>> def foo():
178 ... x = 10
179 ... def bar():
180 ... nonlocal x
181 ... print(x)
182 ... x += 1
183 ... bar()
184 ... print(x)
185 ...
186 >>> foo()
187 10
188 11
189
190
191 What are the rules for local and global variables in Python?
192 ------------------------------------------------------------
193
194 In Python, variables that are only referenced inside a function are implicitly
195 global. If a variable is assigned a value anywhere within the function's body,
196 it's assumed to be a local unless explicitly declared as global.
197
198 Though a bit surprising at first, a moment's consideration explains this. On
199 one hand, requiring :keyword:`global` for assigned variables provides a bar
200 against unintended side-effects. On the other hand, if ``global`` was required
201 for all global references, you'd be using ``global`` all the time. You'd have
202 to declare as global every reference to a built-in function or to a component of
203 an imported module. This clutter would defeat the usefulness of the ``global``
204 declaration for identifying side-effects.
205
206
207 Why do lambdas defined in a loop with different values all return the same result?
208 ----------------------------------------------------------------------------------
209
210 Assume you use a for loop to define a few different lambdas (or even plain
211 functions), e.g.::
212
213 >>> squares = []
214 >>> for x in range(5):
215 ... squares.append(lambda: x**2)
216
217 This gives you a list that contains 5 lambdas that calculate ``x**2``. You
218 might expect that, when called, they would return, respectively, ``0``, ``1``,
219 ``4``, ``9``, and ``16``. However, when you actually try you will see that
220 they all return ``16``::
221
222 >>> squares[2]()
223 16
224 >>> squares[4]()
225 16
226
227 This happens because ``x`` is not local to the lambdas, but is defined in
228 the outer scope, and it is accessed when the lambda is called --- not when it
229 is defined. At the end of the loop, the value of ``x`` is ``4``, so all the
230 functions now return ``4**2``, i.e. ``16``. You can also verify this by
231 changing the value of ``x`` and see how the results of the lambdas change::
232
233 >>> x = 8
234 >>> squares[2]()
235 64
236
237 In order to avoid this, you need to save the values in variables local to the
238 lambdas, so that they don't rely on the value of the global ``x``::
239
240 >>> squares = []
241 >>> for x in range(5):
242 ... squares.append(lambda n=x: n**2)
243
244 Here, ``n=x`` creates a new variable ``n`` local to the lambda and computed
245 when the lambda is defined so that it has the same value that ``x`` had at
246 that point in the loop. This means that the value of ``n`` will be ``0``
247 in the first lambda, ``1`` in the second, ``2`` in the third, and so on.
248 Therefore each lambda will now return the correct result::
249
250 >>> squares[2]()
251 4
252 >>> squares[4]()
253 16
254
255 Note that this behaviour is not peculiar to lambdas, but applies to regular
256 functions too.
257
258
259 How do I share global variables across modules?
260 ------------------------------------------------
261
262 The canonical way to share information across modules within a single program is
263 to create a special module (often called config or cfg). Just import the config
264 module in all modules of your application; the module then becomes available as
265 a global name. Because there is only one instance of each module, any changes
266 made to the module object get reflected everywhere. For example:
267
268 config.py::
269
270 x = 0 # Default value of the 'x' configuration setting
271
272 mod.py::
273
274 import config
275 config.x = 1
276
277 main.py::
278
279 import config
280 import mod
281 print(config.x)
282
283 Note that using a module is also the basis for implementing the singleton design
284 pattern, for the same reason.
285
286
287 What are the "best practices" for using import in a module?
288 -----------------------------------------------------------
289
290 In general, don't use ``from modulename import *``. Doing so clutters the
291 importer's namespace, and makes it much harder for linters to detect undefined
292 names.
293
294 Import modules at the top of a file. Doing so makes it clear what other modules
295 your code requires and avoids questions of whether the module name is in scope.
296 Using one import per line makes it easy to add and delete module imports, but
297 using multiple imports per line uses less screen space.
298
299 It's good practice if you import modules in the following order:
300
301 1. standard library modules -- e.g. :mod:`sys`, :mod:`os`, :mod:`argparse`, :mod:`re`
302 2. third-party library modules (anything installed in Python's site-packages
303 directory) -- e.g. :mod:`!dateutil`, :mod:`!requests`, :mod:`!PIL.Image`
304 3. locally developed modules
305
306 It is sometimes necessary to move imports to a function or class to avoid
307 problems with circular imports. Gordon McMillan says:
308
309 Circular imports are fine where both modules use the "import <module>" form
310 of import. They fail when the 2nd module wants to grab a name out of the
311 first ("from module import name") and the import is at the top level. That's
312 because names in the 1st are not yet available, because the first module is
313 busy importing the 2nd.
314
315 In this case, if the second module is only used in one function, then the import
316 can easily be moved into that function. By the time the import is called, the
317 first module will have finished initializing, and the second module can do its
318 import.
319
320 It may also be necessary to move imports out of the top level of code if some of
321 the modules are platform-specific. In that case, it may not even be possible to
322 import all of the modules at the top of the file. In this case, importing the
323 correct modules in the corresponding platform-specific code is a good option.
324
325 Only move imports into a local scope, such as inside a function definition, if
326 it's necessary to solve a problem such as avoiding a circular import or are
327 trying to reduce the initialization time of a module. This technique is
328 especially helpful if many of the imports are unnecessary depending on how the
329 program executes. You may also want to move imports into a function if the
330 modules are only ever used in that function. Note that loading a module the
331 first time may be expensive because of the one time initialization of the
332 module, but loading a module multiple times is virtually free, costing only a
333 couple of dictionary lookups. Even if the module name has gone out of scope,
334 the module is probably available in :data:`sys.modules`.
335
336
337 Why are default values shared between objects?
338 ----------------------------------------------
339
340 This type of bug commonly bites neophyte programmers. Consider this function::
341
342 def foo(mydict={}): # Danger: shared reference to one dict for all calls
343 ... compute something ...
344 mydict[key] = value
345 return mydict
346
347 The first time you call this function, ``mydict`` contains a single item. The
348 second time, ``mydict`` contains two items because when ``foo()`` begins
349 executing, ``mydict`` starts out with an item already in it.
350
351 It is often expected that a function call creates new objects for default
352 values. This is not what happens. Default values are created exactly once, when
353 the function is defined. If that object is changed, like the dictionary in this
354 example, subsequent calls to the function will refer to this changed object.
355
356 By definition, immutable objects such as numbers, strings, tuples, and ``None``,
357 are safe from change. Changes to mutable objects such as dictionaries, lists,
358 and class instances can lead to confusion.
359
360 Because of this feature, it is good programming practice to not use mutable
361 objects as default values. Instead, use ``None`` as the default value and
362 inside the function, check if the parameter is ``None`` and create a new
363 list/dictionary/whatever if it is. For example, don't write::
364
365 def foo(mydict={}):
366 ...
367
368 but::
369
370 def foo(mydict=None):
371 if mydict is None:
372 mydict = {} # create a new dict for local namespace
373
374 This feature can be useful. When you have a function that's time-consuming to
375 compute, a common technique is to cache the parameters and the resulting value
376 of each call to the function, and return the cached value if the same value is
377 requested again. This is called "memoizing", and can be implemented like this::
378
379 # Callers can only provide two parameters and optionally pass _cache by keyword
380 def expensive(arg1, arg2, *, _cache={}):
381 if (arg1, arg2) in _cache:
382 return _cache[(arg1, arg2)]
383
384 # Calculate the value
385 result = ... expensive computation ...
386 _cache[(arg1, arg2)] = result # Store result in the cache
387 return result
388
389 You could use a global variable containing a dictionary instead of the default
390 value; it's a matter of taste.
391
392
393 How can I pass optional or keyword parameters from one function to another?
394 ---------------------------------------------------------------------------
395
396 Collect the arguments using the ``*`` and ``**`` specifiers in the function's
397 parameter list; this gives you the positional arguments as a tuple and the
398 keyword arguments as a dictionary. You can then pass these arguments when
399 calling another function by using ``*`` and ``**``::
400
401 def f(x, *args, **kwargs):
402 ...
403 kwargs['width'] = '14.3c'
404 ...
405 g(x, *args, **kwargs)
406
407
408 .. index::
409 single: argument; difference from parameter
410 single: parameter; difference from argument
411
412 .. _faq-argument-vs-parameter:
413
414 What is the difference between arguments and parameters?
415 --------------------------------------------------------
416
417 :term:`Parameters <parameter>` are defined by the names that appear in a
418 function definition, whereas :term:`arguments <argument>` are the values
419 actually passed to a function when calling it. Parameters define what
420 :term:`kind of arguments <parameter>` a function can accept. For
421 example, given the function definition::
422
423 def func(foo, bar=None, **kwargs):
424 pass
425
426 *foo*, *bar* and *kwargs* are parameters of ``func``. However, when calling
427 ``func``, for example::
428
429 func(42, bar=314, extra=somevar)
430
431 the values ``42``, ``314``, and ``somevar`` are arguments.
432
433
434 Why did changing list 'y' also change list 'x'?
435 ------------------------------------------------
436
437 If you wrote code like::
438
439 >>> x = []
440 >>> y = x
441 >>> y.append(10)
442 >>> y
443 [10]
444 >>> x
445 [10]
446
447 you might be wondering why appending an element to ``y`` changed ``x`` too.
448
449 There are two factors that produce this result:
450
451 1) Variables are simply names that refer to objects. Doing ``y = x`` doesn't
452 create a copy of the list -- it creates a new variable ``y`` that refers to
453 the same object ``x`` refers to. This means that there is only one object
454 (the list), and both ``x`` and ``y`` refer to it.
455 2) Lists are :term:`mutable`, which means that you can change their content.
456
457 After the call to :meth:`~sequence.append`, the content of the mutable object has
458 changed from ``[]`` to ``[10]``. Since both the variables refer to the same
459 object, using either name accesses the modified value ``[10]``.
460
461 If we instead assign an immutable object to ``x``::
462
463 >>> x = 5 # ints are immutable
464 >>> y = x
465 >>> x = x + 1 # 5 can't be mutated, we are creating a new object here
466 >>> x
467 6
468 >>> y
469 5
470
471 we can see that in this case ``x`` and ``y`` are not equal anymore. This is
472 because integers are :term:`immutable`, and when we do ``x = x + 1`` we are not
473 mutating the int ``5`` by incrementing its value; instead, we are creating a
474 new object (the int ``6``) and assigning it to ``x`` (that is, changing which
475 object ``x`` refers to). After this assignment we have two objects (the ints
476 ``6`` and ``5``) and two variables that refer to them (``x`` now refers to
477 ``6`` but ``y`` still refers to ``5``).
478
479 Some operations (for example ``y.append(10)`` and ``y.sort()``) mutate the
480 object, whereas superficially similar operations (for example ``y = y + [10]``
481 and :func:`sorted(y) <sorted>`) create a new object. In general in Python (and in all cases
482 in the standard library) a method that mutates an object will return ``None``
483 to help avoid getting the two types of operations confused. So if you
484 mistakenly write ``y.sort()`` thinking it will give you a sorted copy of ``y``,
485 you'll instead end up with ``None``, which will likely cause your program to
486 generate an easily diagnosed error.
487
488 However, there is one class of operations where the same operation sometimes
489 has different behaviors with different types: the augmented assignment
490 operators. For example, ``+=`` mutates lists but not tuples or ints (``a_list
491 += [1, 2, 3]`` is equivalent to ``a_list.extend([1, 2, 3])`` and mutates
492 ``a_list``, whereas ``some_tuple += (1, 2, 3)`` and ``some_int += 1`` create
493 new objects).
494
495 In other words:
496
497 * If we have a mutable object (:class:`list`, :class:`dict`, :class:`set`,
498 etc.), we can use some specific operations to mutate it and all the variables
499 that refer to it will see the change.
500 * If we have an immutable object (:class:`str`, :class:`int`, :class:`tuple`,
501 etc.), all the variables that refer to it will always see the same value,
502 but operations that transform that value into a new value always return a new
503 object.
504
505 If you want to know if two variables refer to the same object or not, you can
506 use the :keyword:`is` operator, or the built-in function :func:`id`.
507
508
509 How do I write a function with output parameters (call by reference)?
510 ---------------------------------------------------------------------
511
512 Remember that arguments are passed by assignment in Python. Since assignment
513 just creates references to objects, there's no alias between an argument name in
514 the caller and callee, and so no call-by-reference per se. You can achieve the
515 desired effect in a number of ways.
516
517 1) By returning a tuple of the results::
518
519 >>> def func1(a, b):
520 ... a = 'new-value' # a and b are local names
521 ... b = b + 1 # assigned to new objects
522 ... return a, b # return new values
523 ...
524 >>> x, y = 'old-value', 99
525 >>> func1(x, y)
526 ('new-value', 100)
527
528 This is almost always the clearest solution.
529
530 2) By using global variables. This isn't thread-safe, and is not recommended.
531
532 3) By passing a mutable (changeable in-place) object::
533
534 >>> def func2(a):
535 ... a[0] = 'new-value' # 'a' references a mutable list
536 ... a[1] = a[1] + 1 # changes a shared object
537 ...
538 >>> args = ['old-value', 99]
539 >>> func2(args)
540 >>> args
541 ['new-value', 100]
542
543 4) By passing in a dictionary that gets mutated::
544
545 >>> def func3(args):
546 ... args['a'] = 'new-value' # args is a mutable dictionary
547 ... args['b'] = args['b'] + 1 # change it in-place
548 ...
549 >>> args = {'a': 'old-value', 'b': 99}
550 >>> func3(args)
551 >>> args
552 {'a': 'new-value', 'b': 100}
553
554 5) Or bundle up values in a class instance::
555
556 >>> class Namespace:
557 ... def __init__(self, /, **args):
558 ... for key, value in args.items():
559 ... setattr(self, key, value)
560 ...
561 >>> def func4(args):
562 ... args.a = 'new-value' # args is a mutable Namespace
563 ... args.b = args.b + 1 # change object in-place
564 ...
565 >>> args = Namespace(a='old-value', b=99)
566 >>> func4(args)
567 >>> vars(args)
568 {'a': 'new-value', 'b': 100}
569
570
571 There's almost never a good reason to get this complicated.
572
573 Your best choice is to return a tuple containing the multiple results.
574
575
576 How do you make a higher order function in Python?
577 --------------------------------------------------
578
579 You have two choices: you can use nested scopes or you can use callable objects.
580 For example, suppose you wanted to define ``linear(a,b)`` which returns a
581 function ``f(x)`` that computes the value ``a*x+b``. Using nested scopes::
582
583 def linear(a, b):
584 def result(x):
585 return a * x + b
586 return result
587
588 Or using a callable object::
589
590 class linear:
591
592 def __init__(self, a, b):
593 self.a, self.b = a, b
594
595 def __call__(self, x):
596 return self.a * x + self.b
597
598 In both cases, ::
599
600 taxes = linear(0.3, 2)
601
602 gives a callable object where ``taxes(10e6) == 0.3 * 10e6 + 2``.
603
604 The callable object approach has the disadvantage that it is a bit slower and
605 results in slightly longer code. However, note that a collection of callables
606 can share their signature via inheritance::
607
608 class exponential(linear):
609 # __init__ inherited
610 def __call__(self, x):
611 return self.a * (x ** self.b)
612
613 Object can encapsulate state for several methods::
614
615 class counter:
616
617 value = 0
618
619 def set(self, x):
620 self.value = x
621
622 def up(self):
623 self.value = self.value + 1
624
625 def down(self):
626 self.value = self.value - 1
627
628 count = counter()
629 inc, dec, reset = count.up, count.down, count.set
630
631 Here ``inc()``, ``dec()`` and ``reset()`` act like functions which share the
632 same counting variable.
633
634
635 How do I copy an object in Python?
636 ----------------------------------
637
638 In general, try :func:`copy.copy` or :func:`copy.deepcopy` for the general case.
639 Not all objects can be copied, but most can.
640
641 Some objects can be copied more easily. Dictionaries have a :meth:`~dict.copy`
642 method::
643
644 newdict = olddict.copy()
645
646 Sequences can be copied by slicing::
647
648 new_l = l[:]
649
650
651 How can I find the methods or attributes of an object?
652 ------------------------------------------------------
653
654 For an instance ``x`` of a user-defined class, :func:`dir(x) <dir>` returns an alphabetized
655 list of the names containing the instance attributes and methods and attributes
656 defined by its class.
657
658
659 How can my code discover the name of an object?
660 -----------------------------------------------
661
662 Generally speaking, it can't, because objects don't really have names.
663 Essentially, assignment always binds a name to a value; the same is true of
664 ``def`` and ``class`` statements, but in that case the value is a
665 callable. Consider the following code::
666
667 >>> class A:
668 ... pass
669 ...
670 >>> B = A
671 >>> a = B()
672 >>> b = a
673 >>> print(b)
674 <__main__.A object at 0x16D07CC>
675 >>> print(a)
676 <__main__.A object at 0x16D07CC>
677
678 Arguably the class has a name: even though it is bound to two names and invoked
679 through the name ``B`` the created instance is still reported as an instance of
680 class ``A``. However, it is impossible to say whether the instance's name is ``a`` or
681 ``b``, since both names are bound to the same value.
682
683 Generally speaking it should not be necessary for your code to "know the names"
684 of particular values. Unless you are deliberately writing introspective
685 programs, this is usually an indication that a change of approach might be
686 beneficial.
687
688 In comp.lang.python, Fredrik Lundh once gave an excellent analogy in answer to
689 this question:
690
691 The same way as you get the name of that cat you found on your porch: the cat
692 (object) itself cannot tell you its name, and it doesn't really care -- so
693 the only way to find out what it's called is to ask all your neighbours
694 (namespaces) if it's their cat (object)...
695
696 ....and don't be surprised if you'll find that it's known by many names, or
697 no name at all!
698
699
700 What's up with the comma operator's precedence?
701 -----------------------------------------------
702
703 Comma is not an operator in Python. Consider this session::
704
705 >>> "a" in "b", "a"
706 (False, 'a')
707
708 Since the comma is not an operator, but a separator between expressions the
709 above is evaluated as if you had entered::
710
711 ("a" in "b"), "a"
712
713 not::
714
715 "a" in ("b", "a")
716
717 The same is true of the various assignment operators (``=``, ``+=`` etc). They
718 are not truly operators but syntactic delimiters in assignment statements.
719
720
721 Is there an equivalent of C's "?:" ternary operator?
722 ----------------------------------------------------
723
724 Yes, there is. The syntax is as follows::
725
726 [on_true] if [expression] else [on_false]
727
728 x, y = 50, 25
729 small = x if x < y else y
730
731 Before this syntax was introduced in Python 2.5, a common idiom was to use
732 logical operators::
733
734 [expression] and [on_true] or [on_false]
735
736 However, this idiom is unsafe, as it can give wrong results when *on_true*
737 has a false boolean value. Therefore, it is always better to use
738 the ``... if ... else ...`` form.
739
740
741 Is it possible to write obfuscated one-liners in Python?
742 --------------------------------------------------------
743
744 Yes. Usually this is done by nesting :keyword:`lambda` within
745 :keyword:`!lambda`. See the following three examples, slightly adapted from Ulf Bartelt::
746
747 from functools import reduce
748
749 # Primes < 1000
750 print(list(filter(None,map(lambda y:y*reduce(lambda x,y:x*y!=0,
751 map(lambda x,y=y:y%x,range(2,int(pow(y,0.5)+1))),1),range(2,1000)))))
752
753 # First 10 Fibonacci numbers
754 print(list(map(lambda x,f=lambda x,f:(f(x-1,f)+f(x-2,f)) if x>1 else 1:
755 f(x,f), range(10))))
756
757 # Mandelbrot set
758 print((lambda Ru,Ro,Iu,Io,IM,Sx,Sy:reduce(lambda x,y:x+'\n'+y,map(lambda y,
759 Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,Sy=Sy,L=lambda yc,Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,i=IM,
760 Sx=Sx,Sy=Sy:reduce(lambda x,y:x+y,map(lambda x,xc=Ru,yc=yc,Ru=Ru,Ro=Ro,
761 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
762 >=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(
763 64+F(Ru+x*(Ro-Ru)/Sx,yc,0,0,i)),range(Sx))):L(Iu+y*(Io-Iu)/Sy),range(Sy
764 ))))(-2.1, 0.7, -1.2, 1.2, 30, 80, 24))
765 # \___ ___/ \___ ___/ | | |__ lines on screen
766 # V V | |______ columns on screen
767 # | | |__________ maximum of "iterations"
768 # | |_________________ range on y axis
769 # |____________________________ range on x axis
770
771 Don't try this at home, kids!
772
773
774 .. _faq-positional-only-arguments:
775
776 What does the slash(/) in the parameter list of a function mean?
777 ----------------------------------------------------------------
778
779 A slash in the argument list of a function denotes that the parameters prior to
780 it are positional-only. Positional-only parameters are the ones without an
781 externally usable name. Upon calling a function that accepts positional-only
782 parameters, arguments are mapped to parameters based solely on their position.
783 For example, :func:`divmod` is a function that accepts positional-only
784 parameters. Its documentation looks like this::
785
786 >>> help(divmod)
787 Help on built-in function divmod in module builtins:
788
789 divmod(x, y, /)
790 Return the tuple (x//y, x%y). Invariant: div*y + mod == x.
791
792 The slash at the end of the parameter list means that both parameters are
793 positional-only. Thus, calling :func:`divmod` with keyword arguments would lead
794 to an error::
795
796 >>> divmod(x=3, y=4)
797 Traceback (most recent call last):
798 File "<stdin>", line 1, in <module>
799 TypeError: divmod() takes no keyword arguments
800
801
802 Numbers and strings
803 ===================
804
805 How do I specify hexadecimal and octal integers?
806 ------------------------------------------------
807
808 To specify an octal digit, precede the octal value with a zero, and then a lower
809 or uppercase "o". For example, to set the variable "a" to the octal value "10"
810 (8 in decimal), type::
811
812 >>> a = 0o10
813 >>> a
814 8
815
816 Hexadecimal is just as easy. Simply precede the hexadecimal number with a zero,
817 and then a lower or uppercase "x". Hexadecimal digits can be specified in lower
818 or uppercase. For example, in the Python interpreter::
819
820 >>> a = 0xa5
821 >>> a
822 165
823 >>> b = 0XB2
824 >>> b
825 178
826
827
828 Why does -22 // 10 return -3?
829 -----------------------------
830
831 It's primarily driven by the desire that ``i % j`` have the same sign as ``j``.
832 If you want that, and also want::
833
834 i == (i // j) * j + (i % j)
835
836 then integer division has to return the floor. C also requires that identity to
837 hold, and then compilers that truncate ``i // j`` need to make ``i % j`` have
838 the same sign as ``i``.
839
840 There are few real use cases for ``i % j`` when ``j`` is negative. When ``j``
841 is positive, there are many, and in virtually all of them it's more useful for
842 ``i % j`` to be ``>= 0``. If the clock says 10 now, what did it say 200 hours
843 ago? ``-190 % 12 == 2`` is useful; ``-190 % 12 == -10`` is a bug waiting to
844 bite.
845
846
847 How do I get int literal attribute instead of SyntaxError?
848 ----------------------------------------------------------
849
850 Trying to lookup an ``int`` literal attribute in the normal manner gives
851 a :exc:`SyntaxError` because the period is seen as a decimal point::
852
853 >>> 1.__class__
854 File "<stdin>", line 1
855 1.__class__
856 ^
857 SyntaxError: invalid decimal literal
858
859 The solution is to separate the literal from the period
860 with either a space or parentheses.
861
862 >>> 1 .__class__
863 <class 'int'>
864 >>> (1).__class__
865 <class 'int'>
866
867
868 How do I convert a string to a number?
869 --------------------------------------
870
871 For integers, use the built-in :func:`int` type constructor, e.g. ``int('144')
872 == 144``. Similarly, :func:`float` converts to a floating-point number,
873 e.g. ``float('144') == 144.0``.
874
875 By default, these interpret the number as decimal, so that ``int('0144') ==
876 144`` holds true, and ``int('0x144')`` raises :exc:`ValueError`. ``int(string,
877 base)`` takes the base to convert from as a second optional argument, so ``int(
878 '0x144', 16) == 324``. If the base is specified as 0, the number is interpreted
879 using Python's rules: a leading '0o' indicates octal, and '0x' indicates a hex
880 number.
881
882 Do not use the built-in function :func:`eval` if all you need is to convert
883 strings to numbers. :func:`eval` will be significantly slower and it presents a
884 security risk: someone could pass you a Python expression that might have
885 unwanted side effects. For example, someone could pass
886 ``__import__('os').system("rm -rf $HOME")`` which would erase your home
887 directory.
888
889 :func:`eval` also has the effect of interpreting numbers as Python expressions,
890 so that e.g. ``eval('09')`` gives a syntax error because Python does not allow
891 leading '0' in a decimal number (except '0').
892
893
894 How do I convert a number to a string?
895 --------------------------------------
896
897 To convert, e.g., the number ``144`` to the string ``'144'``, use the built-in type
898 constructor :func:`str`. If you want a hexadecimal or octal representation, use
899 the built-in functions :func:`hex` or :func:`oct`. For fancy formatting, see
900 the :ref:`f-strings` and :ref:`formatstrings` sections,
901 e.g. ``"{:04d}".format(144)`` yields
902 ``'0144'`` and ``"{:.3f}".format(1.0/3.0)`` yields ``'0.333'``.
903
904
905 How do I modify a string in place?
906 ----------------------------------
907
908 You can't, because strings are immutable. In most situations, you should
909 simply construct a new string from the various parts you want to assemble
910 it from. However, if you need an object with the ability to modify in-place
911 unicode data, try using an :class:`io.StringIO` object or the :mod:`array`
912 module::
913
914 >>> import io
915 >>> s = "Hello, world"
916 >>> sio = io.StringIO(s)
917 >>> sio.getvalue()
918 'Hello, world'
919 >>> sio.seek(7)
920 7
921 >>> sio.write("there!")
922 6
923 >>> sio.getvalue()
924 'Hello, there!'
925
926 >>> import array
927 >>> a = array.array('w', s)
928 >>> print(a)
929 array('w', 'Hello, world')
930 >>> a[0] = 'y'
931 >>> print(a)
932 array('w', 'yello, world')
933 >>> a.tounicode()
934 'yello, world'
935
936
937 How do I use strings to call functions/methods?
938 -----------------------------------------------
939
940 There are various techniques.
941
942 * The best is to use a dictionary that maps strings to functions. The primary
943 advantage of this technique is that the strings do not need to match the names
944 of the functions. This is also the primary technique used to emulate a case
945 construct::
946
947 def a():
948 pass
949
950 def b():
951 pass
952
953 dispatch = {'go': a, 'stop': b} # Note lack of parens for funcs
954
955 dispatch[get_input()]() # Note trailing parens to call function
956
957 * Use the built-in function :func:`getattr`::
958
959 import foo
960 getattr(foo, 'bar')()
961
962 Note that :func:`getattr` works on any object, including classes, class
963 instances, modules, and so on.
964
965 This is used in several places in the standard library, like this::
966
967 class Foo:
968 def do_foo(self):
969 ...
970
971 def do_bar(self):
972 ...
973
974 f = getattr(foo_instance, 'do_' + opname)
975 f()
976
977
978 * Use :func:`locals` to resolve the function name::
979
980 def myFunc():
981 print("hello")
982
983 fname = "myFunc"
984
985 f = locals()[fname]
986 f()
987
988
989 Is there an equivalent to Perl's ``chomp()`` for removing trailing newlines from strings?
990 -----------------------------------------------------------------------------------------
991
992 You can use ``S.rstrip("\r\n")`` to remove all occurrences of any line
993 terminator from the end of the string ``S`` without removing other trailing
994 whitespace. If the string ``S`` represents more than one line, with several
995 empty lines at the end, the line terminators for all the blank lines will
996 be removed::
997
998 >>> lines = ("line 1 \r\n"
999 ... "\r\n"
1000 ... "\r\n")
1001 >>> lines.rstrip("\n\r")
1002 'line 1 '
1003
1004 Since this is typically only desired when reading text one line at a time, using
1005 ``S.rstrip()`` this way works well.
1006
1007
1008 Is there a ``scanf()`` or ``sscanf()`` equivalent?
1009 --------------------------------------------------
1010
1011 Not as such.
1012
1013 For simple input parsing, the easiest approach is usually to split the line into
1014 whitespace-delimited words using the :meth:`~str.split` method of string objects
1015 and then convert decimal strings to numeric values using :func:`int` or
1016 :func:`float`. :meth:`!split` supports an optional "sep" parameter which is useful
1017 if the line uses something other than whitespace as a separator.
1018
1019 For more complicated input parsing, regular expressions are more powerful
1020 than C's ``sscanf`` and better suited for the task.
1021
1022
1023 What does ``UnicodeDecodeError`` or ``UnicodeEncodeError`` error mean?
1024 ----------------------------------------------------------------------
1025
1026 See the :ref:`unicode-howto`.
1027
1028
1029 .. _faq-programming-raw-string-backslash:
1030
1031 Can I end a raw string with an odd number of backslashes?
1032 ---------------------------------------------------------
1033
1034 A raw string ending with an odd number of backslashes will escape the string's quote::
1035
1036 >>> r'C:\this\will\not\work\'
1037 File "<stdin>", line 1
1038 r'C:\this\will\not\work\'
1039 ^
1040 SyntaxError: unterminated string literal (detected at line 1)
1041
1042 There are several workarounds for this. One is to use regular strings and double
1043 the backslashes::
1044
1045 >>> 'C:\\this\\will\\work\\'
1046 'C:\\this\\will\\work\\'
1047
1048 Another is to concatenate a regular string containing an escaped backslash to the
1049 raw string::
1050
1051 >>> r'C:\this\will\work' '\\'
1052 'C:\\this\\will\\work\\'
1053
1054 It is also possible to use :func:`os.path.join` to append a backslash on Windows::
1055
1056 >>> os.path.join(r'C:\this\will\work', '')
1057 'C:\\this\\will\\work\\'
1058
1059 Note that while a backslash will "escape" a quote for the purposes of
1060 determining where the raw string ends, no escaping occurs when interpreting the
1061 value of the raw string. That is, the backslash remains present in the value of
1062 the raw string::
1063
1064 >>> r'backslash\'preserved'
1065 "backslash\\'preserved"
1066
1067 Also see the specification in the :ref:`language reference <strings>`.
1068
1069 Performance
1070 ===========
1071
1072 My program is too slow. How do I speed it up?
1073 ---------------------------------------------
1074
1075 That's a tough one, in general. First, here are a list of things to
1076 remember before diving further:
1077
1078 * Performance characteristics vary across Python implementations. This FAQ
1079 focuses on :term:`CPython`.
1080 * Behaviour can vary across operating systems, especially when talking about
1081 I/O or multi-threading.
1082 * You should always find the hot spots in your program *before* attempting to
1083 optimize any code (see the :mod:`profile` module).
1084 * Writing benchmark scripts will allow you to iterate quickly when searching
1085 for improvements (see the :mod:`timeit` module).
1086 * It is highly recommended to have good code coverage (through unit testing
1087 or any other technique) before potentially introducing regressions hidden
1088 in sophisticated optimizations.
1089
1090 That being said, there are many tricks to speed up Python code. Here are
1091 some general principles which go a long way towards reaching acceptable
1092 performance levels:
1093
1094 * Making your algorithms faster (or changing to faster ones) can yield
1095 much larger benefits than trying to sprinkle micro-optimization tricks
1096 all over your code.
1097
1098 * Use the right data structures. Study documentation for the :ref:`bltin-types`
1099 and the :mod:`collections` module.
1100
1101 * When the standard library provides a primitive for doing something, it is
1102 likely (although not guaranteed) to be faster than any alternative you
1103 may come up with. This is doubly true for primitives written in C, such
1104 as builtins and some extension types. For example, be sure to use
1105 either the :meth:`list.sort` built-in method or the related :func:`sorted`
1106 function to do sorting (and see the :ref:`sortinghowto` for examples
1107 of moderately advanced usage).
1108
1109 * Abstractions tend to create indirections and force the interpreter to work
1110 more. If the levels of indirection outweigh the amount of useful work
1111 done, your program will be slower. You should avoid excessive abstraction,
1112 especially under the form of tiny functions or methods (which are also often
1113 detrimental to readability).
1114
1115 If you have reached the limit of what pure Python can allow, there are tools
1116 to take you further away. For example, `Cython <https://cython.org>`_ can
1117 compile a slightly modified version of Python code into a C extension, and
1118 can be used on many different platforms. Cython can take advantage of
1119 compilation (and optional type annotations) to make your code significantly
1120 faster than when interpreted. If you are confident in your C programming
1121 skills, you can also :ref:`write a C extension module <extending-index>`
1122 yourself.
1123
1124 .. seealso::
1125 The wiki page devoted to `performance tips
1126 <https://wiki.python.org/moin/PythonSpeed/PerformanceTips>`_.
1127
1128 .. _efficient_string_concatenation:
1129
1130 What is the most efficient way to concatenate many strings together?
1131 --------------------------------------------------------------------
1132
1133 :class:`str` and :class:`bytes` objects are immutable, therefore concatenating
1134 many strings together is inefficient as each concatenation creates a new
1135 object. In the general case, the total runtime cost is quadratic in the
1136 total string length.
1137
1138 To accumulate many :class:`str` objects, the recommended idiom is to place
1139 them into a list and call :meth:`str.join` at the end::
1140
1141 chunks = []
1142 for s in my_strings:
1143 chunks.append(s)
1144 result = ''.join(chunks)
1145
1146 (another reasonably efficient idiom is to use :class:`io.StringIO`)
1147
1148 To accumulate many :class:`bytes` objects, the recommended idiom is to extend
1149 a :class:`bytearray` object using in-place concatenation (the ``+=`` operator)::
1150
1151 result = bytearray()
1152 for b in my_bytes_objects:
1153 result += b
1154
1155
1156 Sequences (Tuples/Lists)
1157 ========================
1158
1159 How do I convert between tuples and lists?
1160 ------------------------------------------
1161
1162 The type constructor ``tuple(seq)`` converts any sequence (actually, any
1163 iterable) into a tuple with the same items in the same order.
1164
1165 For example, ``tuple([1, 2, 3])`` yields ``(1, 2, 3)`` and ``tuple('abc')``
1166 yields ``('a', 'b', 'c')``. If the argument is a tuple, it does not make a copy
1167 but returns the same object, so it is cheap to call :func:`tuple` when you
1168 aren't sure that an object is already a tuple.
1169
1170 The type constructor ``list(seq)`` converts any sequence or iterable into a list
1171 with the same items in the same order. For example, ``list((1, 2, 3))`` yields
1172 ``[1, 2, 3]`` and ``list('abc')`` yields ``['a', 'b', 'c']``. If the argument
1173 is a list, it makes a copy just like ``seq[:]`` would.
1174
1175
1176 What's a negative index?
1177 ------------------------
1178
1179 Python sequences are indexed with positive numbers and negative numbers. For
1180 positive numbers 0 is the first index 1 is the second index and so forth. For
1181 negative indices -1 is the last index and -2 is the penultimate (next to last)
1182 index and so forth. Think of ``seq[-n]`` as the same as ``seq[len(seq)-n]``.
1183
1184 Using negative indices can be very convenient. For example ``S[:-1]`` is all of
1185 the string except for its last character, which is useful for removing the
1186 trailing newline from a string.
1187
1188
1189 How do I iterate over a sequence in reverse order?
1190 --------------------------------------------------
1191
1192 Use the :func:`reversed` built-in function::
1193
1194 for x in reversed(sequence):
1195 ... # do something with x ...
1196
1197 This won't touch your original sequence, but build a new copy with reversed
1198 order to iterate over.
1199
1200
1201 How do you remove duplicates from a list?
1202 -----------------------------------------
1203
1204 See the Python Cookbook for a long discussion of many ways to do this:
1205
1206 https://code.activestate.com/recipes/52560/
1207
1208 If you don't mind reordering the list, sort it and then scan from the end of the
1209 list, deleting duplicates as you go::
1210
1211 if mylist:
1212 mylist.sort()
1213 last = mylist[-1]
1214 for i in range(len(mylist)-2, -1, -1):
1215 if last == mylist[i]:
1216 del mylist[i]
1217 else:
1218 last = mylist[i]
1219
1220 If all elements of the list may be used as set keys (i.e. they are all
1221 :term:`hashable`) this is often faster ::
1222
1223 mylist = list(set(mylist))
1224
1225 This converts the list into a set, thereby removing duplicates, and then back
1226 into a list.
1227
1228
1229 How do you remove multiple items from a list?
1230 ---------------------------------------------
1231
1232 As with removing duplicates, explicitly iterating in reverse with a
1233 delete condition is one possibility. However, it is easier and faster
1234 to use slice replacement with an implicit or explicit forward iteration.
1235 Here are three variations::
1236
1237 mylist[:] = filter(keep_function, mylist)
1238 mylist[:] = (x for x in mylist if keep_condition)
1239 mylist[:] = [x for x in mylist if keep_condition]
1240
1241 The list comprehension may be fastest.
1242
1243
1244 How do you make an array in Python?
1245 -----------------------------------
1246
1247 Use a list::
1248
1249 ["this", 1, "is", "an", "array"]
1250
1251 Lists are equivalent to C or Pascal arrays in their time complexity; the primary
1252 difference is that a Python list can contain objects of many different types.
1253
1254 The ``array`` module also provides methods for creating arrays of fixed types
1255 with compact representations, but they are slower to index than lists. Also
1256 note that `NumPy <https://numpy.org/>`_
1257 and other third party packages define array-like structures with
1258 various characteristics as well.
1259
1260 To get Lisp-style linked lists, you can emulate *cons cells* using tuples::
1261
1262 lisp_list = ("like", ("this", ("example", None) ) )
1263
1264 If mutability is desired, you could use lists instead of tuples. Here the
1265 analogue of a Lisp *car* is ``lisp_list[0]`` and the analogue of *cdr* is
1266 ``lisp_list[1]``. Only do this if you're sure you really need to, because it's
1267 usually a lot slower than using Python lists.
1268
1269
1270 .. _faq-multidimensional-list:
1271
1272 How do I create a multidimensional list?
1273 ----------------------------------------
1274
1275 You probably tried to make a multidimensional array like this::
1276
1277 >>> A = [[None] * 2] * 3
1278
1279 This looks correct if you print it:
1280
1281 .. testsetup::
1282
1283 A = [[None] * 2] * 3
1284
1285 .. doctest::
1286
1287 >>> A
1288 [[None, None], [None, None], [None, None]]
1289
1290 But when you assign a value, it shows up in multiple places:
1291
1292 .. testsetup::
1293
1294 A = [[None] * 2] * 3
1295
1296 .. doctest::
1297
1298 >>> A[0][0] = 5
1299 >>> A
1300 [[5, None], [5, None], [5, None]]
1301
1302 The reason is that replicating a list with ``*`` doesn't create copies, it only
1303 creates references to the existing objects. The ``*3`` creates a list
1304 containing 3 references to the same list of length two. Changes to one row will
1305 show in all rows, which is almost certainly not what you want.
1306
1307 The suggested approach is to create a list of the desired length first and then
1308 fill in each element with a newly created list::
1309
1310 A = [None] * 3
1311 for i in range(3):
1312 A[i] = [None] * 2
1313
1314 This generates a list containing 3 different lists of length two. You can also
1315 use a list comprehension::
1316
1317 w, h = 2, 3
1318 A = [[None] * w for i in range(h)]
1319
1320 Or, you can use an extension that provides a matrix datatype; `NumPy
1321 <https://numpy.org/>`_ is the best known.
1322
1323
1324 How do I apply a method or function to a sequence of objects?
1325 -------------------------------------------------------------
1326
1327 To call a method or function and accumulate the return values is a list,
1328 a :term:`list comprehension` is an elegant solution::
1329
1330 result = [obj.method() for obj in mylist]
1331
1332 result = [function(obj) for obj in mylist]
1333
1334 To just run the method or function without saving the return values,
1335 a plain :keyword:`for` loop will suffice::
1336
1337 for obj in mylist:
1338 obj.method()
1339
1340 for obj in mylist:
1341 function(obj)
1342
1343 .. _faq-augmented-assignment-tuple-error:
1344
1345 Why does a_tuple[i] += ['item'] raise an exception when the addition works?
1346 ---------------------------------------------------------------------------
1347
1348 This is because of a combination of the fact that augmented assignment
1349 operators are *assignment* operators, and the difference between mutable and
1350 immutable objects in Python.
1351
1352 This discussion applies in general when augmented assignment operators are
1353 applied to elements of a tuple that point to mutable objects, but we'll use
1354 a ``list`` and ``+=`` as our exemplar.
1355
1356 If you wrote::
1357
1358 >>> a_tuple = (1, 2)
1359 >>> a_tuple[0] += 1
1360 Traceback (most recent call last):
1361 ...
1362 TypeError: 'tuple' object does not support item assignment
1363
1364 The reason for the exception should be immediately clear: ``1`` is added to the
1365 object ``a_tuple[0]`` points to (``1``), producing the result object, ``2``,
1366 but when we attempt to assign the result of the computation, ``2``, to element
1367 ``0`` of the tuple, we get an error because we can't change what an element of
1368 a tuple points to.
1369
1370 Under the covers, what this augmented assignment statement is doing is
1371 approximately this::
1372
1373 >>> result = a_tuple[0] + 1
1374 >>> a_tuple[0] = result
1375 Traceback (most recent call last):
1376 ...
1377 TypeError: 'tuple' object does not support item assignment
1378
1379 It is the assignment part of the operation that produces the error, since a
1380 tuple is immutable.
1381
1382 When you write something like::
1383
1384 >>> a_tuple = (['foo'], 'bar')
1385 >>> a_tuple[0] += ['item']
1386 Traceback (most recent call last):
1387 ...
1388 TypeError: 'tuple' object does not support item assignment
1389
1390 The exception is a bit more surprising, and even more surprising is the fact
1391 that even though there was an error, the append worked::
1392
1393 >>> a_tuple[0]
1394 ['foo', 'item']
1395
1396 To see why this happens, you need to know that (a) if an object implements an
1397 :meth:`~object.__iadd__` magic method, it gets called when the ``+=`` augmented
1398 assignment
1399 is executed, and its return value is what gets used in the assignment statement;
1400 and (b) for lists, :meth:`!__iadd__` is equivalent to calling
1401 :meth:`~sequence.extend` on the list and returning the list.
1402 That's why we say that for lists, ``+=`` is a "shorthand" for :meth:`list.extend`::
1403
1404 >>> a_list = []
1405 >>> a_list += [1]
1406 >>> a_list
1407 [1]
1408
1409 This is equivalent to::
1410
1411 >>> result = a_list.__iadd__([1])
1412 >>> a_list = result
1413
1414 The object pointed to by a_list has been mutated, and the pointer to the
1415 mutated object is assigned back to ``a_list``. The end result of the
1416 assignment is a no-op, since it is a pointer to the same object that ``a_list``
1417 was previously pointing to, but the assignment still happens.
1418
1419 Thus, in our tuple example what is happening is equivalent to::
1420
1421 >>> result = a_tuple[0].__iadd__(['item'])
1422 >>> a_tuple[0] = result
1423 Traceback (most recent call last):
1424 ...
1425 TypeError: 'tuple' object does not support item assignment
1426
1427 The :meth:`!__iadd__` succeeds, and thus the list is extended, but even though
1428 ``result`` points to the same object that ``a_tuple[0]`` already points to,
1429 that final assignment still results in an error, because tuples are immutable.
1430
1431
1432 I want to do a complicated sort: can you do a Schwartzian Transform in Python?
1433 ------------------------------------------------------------------------------
1434
1435 The technique, attributed to Randal Schwartz of the Perl community, sorts the
1436 elements of a list by a metric which maps each element to its "sort value". In
1437 Python, use the ``key`` argument for the :meth:`list.sort` method::
1438
1439 Isorted = L[:]
1440 Isorted.sort(key=lambda s: int(s[10:15]))
1441
1442
1443 How can I sort one list by values from another list?
1444 ----------------------------------------------------
1445
1446 Merge them into an iterator of tuples, sort the resulting list, and then pick
1447 out the element you want. ::
1448
1449 >>> list1 = ["what", "I'm", "sorting", "by"]
1450 >>> list2 = ["something", "else", "to", "sort"]
1451 >>> pairs = zip(list1, list2)
1452 >>> pairs = sorted(pairs)
1453 >>> pairs
1454 [("I'm", 'else'), ('by', 'sort'), ('sorting', 'to'), ('what', 'something')]
1455 >>> result = [x[1] for x in pairs]
1456 >>> result
1457 ['else', 'sort', 'to', 'something']
1458
1459
1460 Objects
1461 =======
1462
1463 What is a class?
1464 ----------------
1465
1466 A class is the particular object type created by executing a class statement.
1467 Class objects are used as templates to create instance objects, which embody
1468 both the data (attributes) and code (methods) specific to a datatype.
1469
1470 A class can be based on one or more other classes, called its base class(es). It
1471 then inherits the attributes and methods of its base classes. This allows an
1472 object model to be successively refined by inheritance. You might have a
1473 generic ``Mailbox`` class that provides basic accessor methods for a mailbox,
1474 and subclasses such as ``MboxMailbox``, ``MaildirMailbox``, ``OutlookMailbox``
1475 that handle various specific mailbox formats.
1476
1477
1478 What is a method?
1479 -----------------
1480
1481 A method is a function on some object ``x`` that you normally call as
1482 ``x.name(arguments...)``. Methods are defined as functions inside the class
1483 definition::
1484
1485 class C:
1486 def meth(self, arg):
1487 return arg * 2 + self.attribute
1488
1489
1490 What is self?
1491 -------------
1492
1493 Self is merely a conventional name for the first argument of a method. A method
1494 defined as ``meth(self, a, b, c)`` should be called as ``x.meth(a, b, c)`` for
1495 some instance ``x`` of the class in which the definition occurs; the called
1496 method will think it is called as ``meth(x, a, b, c)``.
1497
1498 See also :ref:`why-self`.
1499
1500
1501 How do I check if an object is an instance of a given class or of a subclass of it?
1502 -----------------------------------------------------------------------------------
1503
1504 Use the built-in function :func:`isinstance(obj, cls) <isinstance>`. You can
1505 check if an object
1506 is an instance of any of a number of classes by providing a tuple instead of a
1507 single class, e.g. ``isinstance(obj, (class1, class2, ...))``, and can also
1508 check whether an object is one of Python's built-in types, e.g.
1509 ``isinstance(obj, str)`` or ``isinstance(obj, (int, float, complex))``.
1510
1511 Note that :func:`isinstance` also checks for virtual inheritance from an
1512 :term:`abstract base class`. So, the test will return ``True`` for a
1513 registered class even if hasn't directly or indirectly inherited from it. To
1514 test for "true inheritance", scan the :term:`MRO` of the class:
1515
1516 .. testcode::
1517
1518 from collections.abc import Mapping
1519
1520 class P:
1521 pass
1522
1523 class C(P):
1524 pass
1525
1526 Mapping.register(P)
1527
1528 .. doctest::
1529
1530 >>> c = C()
1531 >>> isinstance(c, C) # direct
1532 True
1533 >>> isinstance(c, P) # indirect
1534 True
1535 >>> isinstance(c, Mapping) # virtual
1536 True
1537
1538 # Actual inheritance chain
1539 >>> type(c).__mro__
1540 (<class 'C'>, <class 'P'>, <class 'object'>)
1541
1542 # Test for "true inheritance"
1543 >>> Mapping in type(c).__mro__
1544 False
1545
1546 Note that most programs do not use :func:`isinstance` on user-defined classes
1547 very often. If you are developing the classes yourself, a more proper
1548 object-oriented style is to define methods on the classes that encapsulate a
1549 particular behaviour, instead of checking the object's class and doing a
1550 different thing based on what class it is. For example, if you have a function
1551 that does something::
1552
1553 def search(obj):
1554 if isinstance(obj, Mailbox):
1555 ... # code to search a mailbox
1556 elif isinstance(obj, Document):
1557 ... # code to search a document
1558 elif ...
1559
1560 A better approach is to define a ``search()`` method on all the classes and just
1561 call it::
1562
1563 class Mailbox:
1564 def search(self):
1565 ... # code to search a mailbox
1566
1567 class Document:
1568 def search(self):
1569 ... # code to search a document
1570
1571 obj.search()
1572
1573
1574 What is delegation?
1575 -------------------
1576
1577 Delegation is an object oriented technique (also called a design pattern).
1578 Let's say you have an object ``x`` and want to change the behaviour of just one
1579 of its methods. You can create a new class that provides a new implementation
1580 of the method you're interested in changing and delegates all other methods to
1581 the corresponding method of ``x``.
1582
1583 Python programmers can easily implement delegation. For example, the following
1584 class implements a class that behaves like a file but converts all written data
1585 to uppercase::
1586
1587 class UpperOut:
1588
1589 def __init__(self, outfile):
1590 self._outfile = outfile
1591
1592 def write(self, s):
1593 self._outfile.write(s.upper())
1594
1595 def __getattr__(self, name):
1596 return getattr(self._outfile, name)
1597
1598 Here the ``UpperOut`` class redefines the ``write()`` method to convert the
1599 argument string to uppercase before calling the underlying
1600 ``self._outfile.write()`` method. All other methods are delegated to the
1601 underlying ``self._outfile`` object. The delegation is accomplished via the
1602 :meth:`~object.__getattr__` method; consult :ref:`the language reference <attribute-access>`
1603 for more information about controlling attribute access.
1604
1605 Note that for more general cases delegation can get trickier. When attributes
1606 must be set as well as retrieved, the class must define a :meth:`~object.__setattr__`
1607 method too, and it must do so carefully. The basic implementation of
1608 :meth:`!__setattr__` is roughly equivalent to the following::
1609
1610 class X:
1611 ...
1612 def __setattr__(self, name, value):
1613 self.__dict__[name] = value
1614 ...
1615
1616 Many :meth:`~object.__setattr__` implementations call :meth:`!object.__setattr__` to set
1617 an attribute on self without causing infinite recursion::
1618
1619 class X:
1620 def __setattr__(self, name, value):
1621 # Custom logic here...
1622 object.__setattr__(self, name, value)
1623
1624 Alternatively, it is possible to set attributes by inserting
1625 entries into :attr:`self.__dict__ <object.__dict__>` directly.
1626
1627
1628 How do I call a method defined in a base class from a derived class that extends it?
1629 ------------------------------------------------------------------------------------
1630
1631 Use the built-in :func:`super` function::
1632
1633 class Derived(Base):
1634 def meth(self):
1635 super().meth() # calls Base.meth
1636
1637 In the example, :func:`super` will automatically determine the instance from
1638 which it was called (the ``self`` value), look up the :term:`method resolution
1639 order` (MRO) with ``type(self).__mro__``, and return the next in line after
1640 ``Derived`` in the MRO: ``Base``.
1641
1642
1643 How can I organize my code to make it easier to change the base class?
1644 ----------------------------------------------------------------------
1645
1646 You could assign the base class to an alias and derive from the alias. Then all
1647 you have to change is the value assigned to the alias. Incidentally, this trick
1648 is also handy if you want to decide dynamically (e.g. depending on availability
1649 of resources) which base class to use. Example::
1650
1651 class Base:
1652 ...
1653
1654 BaseAlias = Base
1655
1656 class Derived(BaseAlias):
1657 ...
1658
1659
1660 How do I create static class data and static class methods?
1661 -----------------------------------------------------------
1662
1663 Both static data and static methods (in the sense of C++ or Java) are supported
1664 in Python.
1665
1666 For static data, simply define a class attribute. To assign a new value to the
1667 attribute, you have to explicitly use the class name in the assignment::
1668
1669 class C:
1670 count = 0 # number of times C.__init__ called
1671
1672 def __init__(self):
1673 C.count = C.count + 1
1674
1675 def getcount(self):
1676 return C.count # or return self.count
1677
1678 ``c.count`` also refers to ``C.count`` for any ``c`` such that ``isinstance(c,
1679 C)`` holds, unless overridden by ``c`` itself or by some class on the base-class
1680 search path from ``c.__class__`` back to ``C``.
1681
1682 Caution: within a method of C, an assignment like ``self.count = 42`` creates a
1683 new and unrelated instance named "count" in ``self``'s own dict. Rebinding of a
1684 class-static data name must always specify the class whether inside a method or
1685 not::
1686
1687 C.count = 314
1688
1689 Static methods are possible::
1690
1691 class C:
1692 @staticmethod
1693 def static(arg1, arg2, arg3):
1694 # No 'self' parameter!
1695 ...
1696
1697 However, a far more straightforward way to get the effect of a static method is
1698 via a simple module-level function::
1699
1700 def getcount():
1701 return C.count
1702
1703 If your code is structured so as to define one class (or tightly related class
1704 hierarchy) per module, this supplies the desired encapsulation.
1705
1706
1707 How can I overload constructors (or methods) in Python?
1708 -------------------------------------------------------
1709
1710 This answer actually applies to all methods, but the question usually comes up
1711 first in the context of constructors.
1712
1713 In C++ you'd write
1714
1715 .. code-block:: c
1716
1717 class C {
1718 C() { cout << "No arguments\n"; }
1719 C(int i) { cout << "Argument is " << i << "\n"; }
1720 }
1721
1722 In Python you have to write a single constructor that catches all cases using
1723 default arguments. For example::
1724
1725 class C:
1726 def __init__(self, i=None):
1727 if i is None:
1728 print("No arguments")
1729 else:
1730 print("Argument is", i)
1731
1732 This is not entirely equivalent, but close enough in practice.
1733
1734 You could also try a variable-length argument list, e.g. ::
1735
1736 def __init__(self, *args):
1737 ...
1738
1739 The same approach works for all method definitions.
1740
1741
1742 I try to use __spam and I get an error about _SomeClassName__spam.
1743 ------------------------------------------------------------------
1744
1745 Variable names with double leading underscores are "mangled" to provide a simple
1746 but effective way to define class private variables. Any identifier of the form
1747 ``__spam`` (at least two leading underscores, at most one trailing underscore)
1748 is textually replaced with ``_classname__spam``, where ``classname`` is the
1749 current class name with any leading underscores stripped.
1750
1751 The identifier can be used unchanged within the class, but to access it outside
1752 the class, the mangled name must be used:
1753
1754 .. code-block:: python
1755
1756 class A:
1757 def __one(self):
1758 return 1
1759 def two(self):
1760 return 2 * self.__one()
1761
1762 class B(A):
1763 def three(self):
1764 return 3 * self._A__one()
1765
1766 four = 4 * A()._A__one()
1767
1768 In particular, this does not guarantee privacy since an outside user can still
1769 deliberately access the private attribute; many Python programmers never bother
1770 to use private variable names at all.
1771
1772 .. seealso::
1773
1774 The :ref:`private name mangling specifications <private-name-mangling>`
1775 for details and special cases.
1776
1777 My class defines __del__ but it is not called when I delete the object.
1778 -----------------------------------------------------------------------
1779
1780 There are several possible reasons for this.
1781
1782 The :keyword:`del` statement does not necessarily call :meth:`~object.__del__` -- it simply
1783 decrements the object's reference count, and if this reaches zero
1784 :meth:`!__del__` is called.
1785
1786 If your data structures contain circular links (e.g. a tree where each child has
1787 a parent reference and each parent has a list of children) the reference counts
1788 will never go back to zero. Once in a while Python runs an algorithm to detect
1789 such cycles, but the garbage collector might run some time after the last
1790 reference to your data structure vanishes, so your :meth:`!__del__` method may be
1791 called at an inconvenient and random time. This is inconvenient if you're trying
1792 to reproduce a problem. Worse, the order in which object's :meth:`!__del__`
1793 methods are executed is arbitrary. You can run :func:`gc.collect` to force a
1794 collection, but there *are* pathological cases where objects will never be
1795 collected.
1796
1797 Despite the cycle collector, it's still a good idea to define an explicit
1798 ``close()`` method on objects to be called whenever you're done with them. The
1799 ``close()`` method can then remove attributes that refer to subobjects. Don't
1800 call :meth:`!__del__` directly -- :meth:`!__del__` should call ``close()`` and
1801 ``close()`` should make sure that it can be called more than once for the same
1802 object.
1803
1804 Another way to avoid cyclical references is to use the :mod:`weakref` module,
1805 which allows you to point to objects without incrementing their reference count.
1806 Tree data structures, for instance, should use weak references for their parent
1807 and sibling references (if they need them!).
1808
1809 .. XXX relevant for Python 3?
1810
1811 If the object has ever been a local variable in a function that caught an
1812 expression in an except clause, chances are that a reference to the object
1813 still exists in that function's stack frame as contained in the stack trace.
1814 Normally, calling :func:`sys.exc_clear` will take care of this by clearing
1815 the last recorded exception.
1816
1817 Finally, if your :meth:`!__del__` method raises an exception, a warning message
1818 is printed to :data:`sys.stderr`.
1819
1820
1821 How do I get a list of all instances of a given class?
1822 ------------------------------------------------------
1823
1824 Python does not keep track of all instances of a class (or of a built-in type).
1825 You can program the class's constructor to keep track of all instances by
1826 keeping a list of weak references to each instance.
1827
1828
1829 Why does the result of ``id()`` appear to be not unique?
1830 --------------------------------------------------------
1831
1832 The :func:`id` builtin returns an integer that is guaranteed to be unique during
1833 the lifetime of the object. Since in CPython, this is the object's memory
1834 address, it happens frequently that after an object is deleted from memory, the
1835 next freshly created object is allocated at the same position in memory. This
1836 is illustrated by this example:
1837
1838 >>> id(1000) # doctest: +SKIP
1839 13901272
1840 >>> id(2000) # doctest: +SKIP
1841 13901272
1842
1843 The two ids belong to different integer objects that are created before, and
1844 deleted immediately after execution of the ``id()`` call. To be sure that
1845 objects whose id you want to examine are still alive, create another reference
1846 to the object:
1847
1848 >>> a = 1000; b = 2000
1849 >>> id(a) # doctest: +SKIP
1850 13901272
1851 >>> id(b) # doctest: +SKIP
1852 13891296
1853
1854
1855 When can I rely on identity tests with the *is* operator?
1856 ---------------------------------------------------------
1857
1858 The ``is`` operator tests for object identity. The test ``a is b`` is
1859 equivalent to ``id(a) == id(b)``.
1860
1861 The most important property of an identity test is that an object is always
1862 identical to itself, ``a is a`` always returns ``True``. Identity tests are
1863 usually faster than equality tests. And unlike equality tests, identity tests
1864 are guaranteed to return a boolean ``True`` or ``False``.
1865
1866 However, identity tests can *only* be substituted for equality tests when
1867 object identity is assured. Generally, there are three circumstances where
1868 identity is guaranteed:
1869
1870 1) Assignments create new names but do not change object identity. After the
1871 assignment ``new = old``, it is guaranteed that ``new is old``.
1872
1873 2) Putting an object in a container that stores object references does not
1874 change object identity. After the list assignment ``s[0] = x``, it is
1875 guaranteed that ``s[0] is x``.
1876
1877 3) If an object is a singleton, it means that only one instance of that object
1878 can exist. After the assignments ``a = None`` and ``b = None``, it is
1879 guaranteed that ``a is b`` because ``None`` is a singleton.
1880
1881 In most other circumstances, identity tests are inadvisable and equality tests
1882 are preferred. In particular, identity tests should not be used to check
1883 constants such as :class:`int` and :class:`str` which aren't guaranteed to be
1884 singletons::
1885
1886 >>> a = 1000
1887 >>> b = 500
1888 >>> c = b + 500
1889 >>> a is c
1890 False
1891
1892 >>> a = 'Python'
1893 >>> b = 'Py'
1894 >>> c = b + 'thon'
1895 >>> a is c
1896 False
1897
1898 Likewise, new instances of mutable containers are never identical::
1899
1900 >>> a = []
1901 >>> b = []
1902 >>> a is b
1903 False
1904
1905 In the standard library code, you will see several common patterns for
1906 correctly using identity tests:
1907
1908 1) As recommended by :pep:`8`, an identity test is the preferred way to check
1909 for ``None``. This reads like plain English in code and avoids confusion
1910 with other objects that may have boolean values that evaluate to false.
1911
1912 2) Detecting optional arguments can be tricky when ``None`` is a valid input
1913 value. In those situations, you can create a singleton sentinel object
1914 guaranteed to be distinct from other objects. For example, here is how
1915 to implement a method that behaves like :meth:`dict.pop`:
1916
1917 .. code-block:: python
1918
1919 _sentinel = object()
1920
1921 def pop(self, key, default=_sentinel):
1922 if key in self:
1923 value = self[key]
1924 del self[key]
1925 return value
1926 if default is _sentinel:
1927 raise KeyError(key)
1928 return default
1929
1930 3) Container implementations sometimes need to augment equality tests with
1931 identity tests. This prevents the code from being confused by objects
1932 such as ``float('NaN')`` that are not equal to themselves.
1933
1934 For example, here is the implementation of
1935 :meth:`!collections.abc.Sequence.__contains__`::
1936
1937 def __contains__(self, value):
1938 for v in self:
1939 if v is value or v == value:
1940 return True
1941 return False
1942
1943
1944 How can a subclass control what data is stored in an immutable instance?
1945 ------------------------------------------------------------------------
1946
1947 When subclassing an immutable type, override the :meth:`~object.__new__` method
1948 instead of the :meth:`~object.__init__` method. The latter only runs *after* an
1949 instance is created, which is too late to alter data in an immutable
1950 instance.
1951
1952 All of these immutable classes have a different signature than their
1953 parent class:
1954
1955 .. testcode::
1956
1957 from datetime import date
1958
1959 class FirstOfMonthDate(date):
1960 "Always choose the first day of the month"
1961 def __new__(cls, year, month, day):
1962 return super().__new__(cls, year, month, 1)
1963
1964 class NamedInt(int):
1965 "Allow text names for some numbers"
1966 xlat = {'zero': 0, 'one': 1, 'ten': 10}
1967 def __new__(cls, value):
1968 value = cls.xlat.get(value, value)
1969 return super().__new__(cls, value)
1970
1971 class TitleStr(str):
1972 "Convert str to name suitable for a URL path"
1973 def __new__(cls, s):
1974 s = s.lower().replace(' ', '-')
1975 s = ''.join([c for c in s if c.isalnum() or c == '-'])
1976 return super().__new__(cls, s)
1977
1978 The classes can be used like this:
1979
1980 .. doctest::
1981
1982 >>> FirstOfMonthDate(2012, 2, 14)
1983 FirstOfMonthDate(2012, 2, 1)
1984 >>> NamedInt('ten')
1985 10
1986 >>> NamedInt(20)
1987 20
1988 >>> TitleStr('Blog: Why Python Rocks')
1989 'blog-why-python-rocks'
1990
1991
1992 .. _faq-cache-method-calls:
1993
1994 How do I cache method calls?
1995 ----------------------------
1996
1997 The two principal tools for caching methods are
1998 :func:`functools.cached_property` and :func:`functools.lru_cache`. The
1999 former stores results at the instance level and the latter at the class
2000 level.
2001
2002 The *cached_property* approach only works with methods that do not take
2003 any arguments. It does not create a reference to the instance. The
2004 cached method result will be kept only as long as the instance is alive.
2005
2006 The advantage is that when an instance is no longer used, the cached
2007 method result will be released right away. The disadvantage is that if
2008 instances accumulate, so too will the accumulated method results. They
2009 can grow without bound.
2010
2011 The *lru_cache* approach works with methods that have :term:`hashable`
2012 arguments. It creates a reference to the instance unless special
2013 efforts are made to pass in weak references.
2014
2015 The advantage of the least recently used algorithm is that the cache is
2016 bounded by the specified *maxsize*. The disadvantage is that instances
2017 are kept alive until they age out of the cache or until the cache is
2018 cleared.
2019
2020 This example shows the various techniques::
2021
2022 class Weather:
2023 "Lookup weather information on a government website"
2024
2025 def __init__(self, station_id):
2026 self._station_id = station_id
2027 # The _station_id is private and immutable
2028
2029 def current_temperature(self):
2030 "Latest hourly observation"
2031 # Do not cache this because old results
2032 # can be out of date.
2033
2034 @cached_property
2035 def location(self):
2036 "Return the longitude/latitude coordinates of the station"
2037 # Result only depends on the station_id
2038
2039 @lru_cache(maxsize=20)
2040 def historic_rainfall(self, date, units='mm'):
2041 "Rainfall on a given date"
2042 # Depends on the station_id, date, and units.
2043
2044 The above example assumes that the *station_id* never changes. If the
2045 relevant instance attributes are mutable, the *cached_property* approach
2046 can't be made to work because it cannot detect changes to the
2047 attributes.
2048
2049 To make the *lru_cache* approach work when the *station_id* is mutable,
2050 the class needs to define the :meth:`~object.__eq__` and :meth:`~object.__hash__`
2051 methods so that the cache can detect relevant attribute updates::
2052
2053 class Weather:
2054 "Example with a mutable station identifier"
2055
2056 def __init__(self, station_id):
2057 self.station_id = station_id
2058
2059 def change_station(self, station_id):
2060 self.station_id = station_id
2061
2062 def __eq__(self, other):
2063 return self.station_id == other.station_id
2064
2065 def __hash__(self):
2066 return hash(self.station_id)
2067
2068 @lru_cache(maxsize=20)
2069 def historic_rainfall(self, date, units='cm'):
2070 'Rainfall on a given date'
2071 # Depends on the station_id, date, and units.
2072
2073
2074 Modules
2075 =======
2076
2077 How do I create a .pyc file?
2078 ----------------------------
2079
2080 When a module is imported for the first time (or when the source file has
2081 changed since the current compiled file was created) a ``.pyc`` file containing
2082 the compiled code should be created in a ``__pycache__`` subdirectory of the
2083 directory containing the ``.py`` file. The ``.pyc`` file will have a
2084 filename that starts with the same name as the ``.py`` file, and ends with
2085 ``.pyc``, with a middle component that depends on the particular ``python``
2086 binary that created it. (See :pep:`3147` for details.)
2087
2088 One reason that a ``.pyc`` file may not be created is a permissions problem
2089 with the directory containing the source file, meaning that the ``__pycache__``
2090 subdirectory cannot be created. This can happen, for example, if you develop as
2091 one user but run as another, such as if you are testing with a web server.
2092
2093 Unless the :envvar:`PYTHONDONTWRITEBYTECODE` environment variable is set,
2094 creation of a .pyc file is automatic if you're importing a module and Python
2095 has the ability (permissions, free space, etc...) to create a ``__pycache__``
2096 subdirectory and write the compiled module to that subdirectory.
2097
2098 Running Python on a top level script is not considered an import and no
2099 ``.pyc`` will be created. For example, if you have a top-level module
2100 ``foo.py`` that imports another module ``xyz.py``, when you run ``foo`` (by
2101 typing ``python foo.py`` as a shell command), a ``.pyc`` will be created for
2102 ``xyz`` because ``xyz`` is imported, but no ``.pyc`` file will be created for
2103 ``foo`` since ``foo.py`` isn't being imported.
2104
2105 If you need to create a ``.pyc`` file for ``foo`` -- that is, to create a
2106 ``.pyc`` file for a module that is not imported -- you can, using the
2107 :mod:`py_compile` and :mod:`compileall` modules.
2108
2109 The :mod:`py_compile` module can manually compile any module. One way is to use
2110 the ``compile()`` function in that module interactively::
2111
2112 >>> import py_compile
2113 >>> py_compile.compile('foo.py') # doctest: +SKIP
2114
2115 This will write the ``.pyc`` to a ``__pycache__`` subdirectory in the same
2116 location as ``foo.py`` (or you can override that with the optional parameter
2117 ``cfile``).
2118
2119 You can also automatically compile all files in a directory or directories using
2120 the :mod:`compileall` module. You can do it from the shell prompt by running
2121 ``compileall.py`` and providing the path of a directory containing Python files
2122 to compile::
2123
2124 python -m compileall .
2125
2126
2127 How do I find the current module name?
2128 --------------------------------------
2129
2130 A module can find out its own module name by looking at the predefined global
2131 variable ``__name__``. If this has the value ``'__main__'``, the program is
2132 running as a script. Many modules that are usually used by importing them also
2133 provide a command-line interface or a self-test, and only execute this code
2134 after checking ``__name__``::
2135
2136 def main():
2137 print('Running test...')
2138 ...
2139
2140 if __name__ == '__main__':
2141 main()
2142
2143
2144 How can I have modules that mutually import each other?
2145 -------------------------------------------------------
2146
2147 Suppose you have the following modules:
2148
2149 :file:`foo.py`::
2150
2151 from bar import bar_var
2152 foo_var = 1
2153
2154 :file:`bar.py`::
2155
2156 from foo import foo_var
2157 bar_var = 2
2158
2159 The problem is that the interpreter will perform the following steps:
2160
2161 * main imports ``foo``
2162 * Empty globals for ``foo`` are created
2163 * ``foo`` is compiled and starts executing
2164 * ``foo`` imports ``bar``
2165 * Empty globals for ``bar`` are created
2166 * ``bar`` is compiled and starts executing
2167 * ``bar`` imports ``foo`` (which is a no-op since there already is a module named ``foo``)
2168 * The import mechanism tries to read ``foo_var`` from ``foo`` globals, to set ``bar.foo_var = foo.foo_var``
2169
2170 The last step fails, because Python isn't done with interpreting ``foo`` yet and
2171 the global symbol dictionary for ``foo`` is still empty.
2172
2173 The same thing happens when you use ``import foo``, and then try to access
2174 ``foo.foo_var`` in global code.
2175
2176 There are (at least) three possible workarounds for this problem.
2177
2178 Guido van Rossum recommends avoiding all uses of ``from <module> import ...``,
2179 and placing all code inside functions. Initializations of global variables and
2180 class variables should use constants or built-in functions only. This means
2181 everything from an imported module is referenced as ``<module>.<name>``.
2182
2183 Jim Roskind suggests performing steps in the following order in each module:
2184
2185 * exports (globals, functions, and classes that don't need imported base
2186 classes)
2187 * ``import`` statements
2188 * active code (including globals that are initialized from imported values).
2189
2190 Van Rossum doesn't like this approach much because the imports appear in a
2191 strange place, but it does work.
2192
2193 Matthias Urlichs recommends restructuring your code so that the recursive import
2194 is not necessary in the first place.
2195
2196 These solutions are not mutually exclusive.
2197
2198
2199 __import__('x.y.z') returns <module 'x'>; how do I get z?
2200 ---------------------------------------------------------
2201
2202 Consider using the convenience function :func:`~importlib.import_module` from
2203 :mod:`importlib` instead::
2204
2205 z = importlib.import_module('x.y.z')
2206
2207
2208 When I edit an imported module and reimport it, the changes don't show up. Why does this happen?
2209 -------------------------------------------------------------------------------------------------
2210
2211 For reasons of efficiency as well as consistency, Python only reads the module
2212 file on the first time a module is imported. If it didn't, in a program
2213 consisting of many modules where each one imports the same basic module, the
2214 basic module would be parsed and re-parsed many times. To force re-reading of a
2215 changed module, do this::
2216
2217 import importlib
2218 import modname
2219 importlib.reload(modname)
2220
2221 Warning: this technique is not 100% fool-proof. In particular, modules
2222 containing statements like ::
2223
2224 from modname import some_objects
2225
2226 will continue to work with the old version of the imported objects. If the
2227 module contains class definitions, existing class instances will *not* be
2228 updated to use the new class definition. This can result in the following
2229 paradoxical behaviour::
2230
2231 >>> import importlib
2232 >>> import cls
2233 >>> c = cls.C() # Create an instance of C
2234 >>> importlib.reload(cls)
2235 <module 'cls' from 'cls.py'>
2236 >>> isinstance(c, cls.C) # isinstance is false?!?
2237 False
2238
2239 The nature of the problem is made clear if you print out the "identity" of the
2240 class objects::
2241
2242 >>> hex(id(c.__class__))
2243 '0x7352a0'
2244 >>> hex(id(cls.C))
2245 '0x4198d0'