1:tocdepth: 2 2 3=============== 4Programming FAQ 5=============== 6 7.. only:: html 8 9 .. contents:: 10 11General Questions 12================= 13 14Is there a source code level debugger with breakpoints, single-stepping, etc.? 15------------------------------------------------------------------------------ 16 17Yes. 18 19Several debuggers for Python are described below, and the built-in function 20:func:`breakpoint` allows you to drop into any of them. 21 22The pdb module is a simple but adequate console-mode debugger for Python. It is 23part of the standard Python library, and is :mod:`documented in the Library 24Reference Manual <pdb>`. You can also write your own debugger by using the code 25for pdb as an example. 26 27The IDLE interactive development environment, which is part of the standard 28Python distribution (normally available as 29`Tools/scripts/idle3 <https://github.com/python/cpython/blob/main/Tools/scripts/idle3>`_), 30includes a graphical debugger. 31 32PythonWin is a Python IDE that includes a GUI debugger based on pdb. The 33PythonWin debugger colors breakpoints and has quite a few cool features such as 34debugging non-PythonWin programs. PythonWin is available as part of 35`pywin32 <https://github.com/mhammond/pywin32>`_ project and 36as 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 40and 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 45tools that integrates with version-control software. 46 47There are a number of commercial Python IDEs that include graphical debuggers. 48They 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 55Are there tools to help find bugs or perform static analysis? 56------------------------------------------------------------- 57 58Yes. 59 60`Pylint <https://pylint.pycqa.org/en/latest/index.html>`_ and 61`Pyflakes <https://github.com/PyCQA/pyflakes>`_ do basic checking that will 62help you catch bugs sooner. 63 64Static 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 67source code. 68 69 70.. _faq-create-standalone-binary: 71 72How can I create a stand-alone binary from a Python script? 73----------------------------------------------------------- 74 75You don't need the ability to compile Python to C code if all you want is a 76stand-alone program that users can download and run without having to install 77the Python distribution first. There are a number of tools that determine the 78set of modules required by a program and bind these modules together with a 79Python binary to produce a single executable. 80 81One 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>`_. 83It converts Python byte code to C arrays; with a C compiler you can 84embed all your modules into a new program, which is then linked with the 85standard Python modules. 86 87It works by scanning your source recursively for import statements (in both 88forms) and looking for the modules in the standard Python path as well as in the 89source directory (for built-in modules). It then turns the bytecode for modules 90written in Python into C code (array initializers that can be turned into code 91objects using the marshal module) and creates a custom-made config file that 92only contains those built-in modules which are actually used in the program. It 93then compiles the generated C code and links it with the rest of the Python 94interpreter to form a self-contained binary which acts exactly like your script. 95 96The following packages can help with the creation of console and GUI 97executables: 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 106Are there coding standards or a style guide for Python programs? 107---------------------------------------------------------------- 108 109Yes. The coding style required for standard library modules is documented as 110:pep:`8`. 111 112 113Core Language 114============= 115 116.. _faq-unboundlocalerror: 117 118Why am I getting an UnboundLocalError when the variable has a value? 119-------------------------------------------------------------------- 120 121It can be a surprise to get the :exc:`UnboundLocalError` in previously working 122code when it is modified by adding an assignment statement somewhere in 123the body of a function. 124 125This code: 126 127 >>> x = 10 128 >>> def bar(): 129 ... print(x) 130 ... 131 >>> bar() 132 10 133 134works, but this code: 135 136 >>> x = 10 137 >>> def foo(): 138 ... print(x) 139 ... x += 1 140 141results in an :exc:`!UnboundLocalError`: 142 143 >>> foo() 144 Traceback (most recent call last): 145 ... 146 UnboundLocalError: local variable 'x' referenced before assignment 147 148This is because when you make an assignment to a variable in a scope, that 149variable becomes local to that scope and shadows any similarly named variable 150in 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 152earlier ``print(x)`` attempts to print the uninitialized local variable and 153an error results. 154 155In the example above you can access the outer scope variable by declaring it 156global: 157 158 >>> x = 10 159 >>> def foobar(): 160 ... global x 161 ... print(x) 162 ... x += 1 163 ... 164 >>> foobar() 165 10 166 167This explicit declaration is required in order to remind you that (unlike the 168superficially analogous situation with class and instance variables) you are 169actually modifying the value of the variable in the outer scope: 170 171 >>> print(x) 172 11 173 174You can do a similar thing in a nested scope using the :keyword:`nonlocal` 175keyword: 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 191What are the rules for local and global variables in Python? 192------------------------------------------------------------ 193 194In Python, variables that are only referenced inside a function are implicitly 195global. If a variable is assigned a value anywhere within the function's body, 196it's assumed to be a local unless explicitly declared as global. 197 198Though a bit surprising at first, a moment's consideration explains this. On 199one hand, requiring :keyword:`global` for assigned variables provides a bar 200against unintended side-effects. On the other hand, if ``global`` was required 201for all global references, you'd be using ``global`` all the time. You'd have 202to declare as global every reference to a built-in function or to a component of 203an imported module. This clutter would defeat the usefulness of the ``global`` 204declaration for identifying side-effects. 205 206 207Why do lambdas defined in a loop with different values all return the same result? 208---------------------------------------------------------------------------------- 209 210Assume you use a for loop to define a few different lambdas (or even plain 211functions), e.g.:: 212 213 >>> squares = [] 214 >>> for x in range(5): 215 ... squares.append(lambda: x**2) 216 217This gives you a list that contains 5 lambdas that calculate ``x**2``. You 218might expect that, when called, they would return, respectively, ``0``, ``1``, 219``4``, ``9``, and ``16``. However, when you actually try you will see that 220they all return ``16``:: 221 222 >>> squares[2]() 223 16 224 >>> squares[4]() 225 16 226 227This happens because ``x`` is not local to the lambdas, but is defined in 228the outer scope, and it is accessed when the lambda is called --- not when it 229is defined. At the end of the loop, the value of ``x`` is ``4``, so all the 230functions now return ``4**2``, i.e. ``16``. You can also verify this by 231changing the value of ``x`` and see how the results of the lambdas change:: 232 233 >>> x = 8 234 >>> squares[2]() 235 64 236 237In order to avoid this, you need to save the values in variables local to the 238lambdas, 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 244Here, ``n=x`` creates a new variable ``n`` local to the lambda and computed 245when the lambda is defined so that it has the same value that ``x`` had at 246that point in the loop. This means that the value of ``n`` will be ``0`` 247in the first lambda, ``1`` in the second, ``2`` in the third, and so on. 248Therefore each lambda will now return the correct result:: 249 250 >>> squares[2]() 251 4 252 >>> squares[4]() 253 16 254 255Note that this behaviour is not peculiar to lambdas, but applies to regular 256functions too. 257 258 259How do I share global variables across modules? 260------------------------------------------------ 261 262The canonical way to share information across modules within a single program is 263to create a special module (often called config or cfg). Just import the config 264module in all modules of your application; the module then becomes available as 265a global name. Because there is only one instance of each module, any changes 266made to the module object get reflected everywhere. For example: 267 268config.py:: 269 270 x = 0 # Default value of the 'x' configuration setting 271 272mod.py:: 273 274 import config 275 config.x = 1 276 277main.py:: 278 279 import config 280 import mod 281 print(config.x) 282 283Note that using a module is also the basis for implementing the singleton design 284pattern, for the same reason. 285 286 287What are the "best practices" for using import in a module? 288----------------------------------------------------------- 289 290In general, don't use ``from modulename import *``. Doing so clutters the 291importer's namespace, and makes it much harder for linters to detect undefined 292names. 293 294Import modules at the top of a file. Doing so makes it clear what other modules 295your code requires and avoids questions of whether the module name is in scope. 296Using one import per line makes it easy to add and delete module imports, but 297using multiple imports per line uses less screen space. 298 299It's good practice if you import modules in the following order: 300 3011. standard library modules -- e.g. :mod:`sys`, :mod:`os`, :mod:`argparse`, :mod:`re` 3022. third-party library modules (anything installed in Python's site-packages 303 directory) -- e.g. :mod:`!dateutil`, :mod:`!requests`, :mod:`!PIL.Image` 3043. locally developed modules 305 306It is sometimes necessary to move imports to a function or class to avoid 307problems 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 315In this case, if the second module is only used in one function, then the import 316can easily be moved into that function. By the time the import is called, the 317first module will have finished initializing, and the second module can do its 318import. 319 320It may also be necessary to move imports out of the top level of code if some of 321the modules are platform-specific. In that case, it may not even be possible to 322import all of the modules at the top of the file. In this case, importing the 323correct modules in the corresponding platform-specific code is a good option. 324 325Only move imports into a local scope, such as inside a function definition, if 326it's necessary to solve a problem such as avoiding a circular import or are 327trying to reduce the initialization time of a module. This technique is 328especially helpful if many of the imports are unnecessary depending on how the 329program executes. You may also want to move imports into a function if the 330modules are only ever used in that function. Note that loading a module the 331first time may be expensive because of the one time initialization of the 332module, but loading a module multiple times is virtually free, costing only a 333couple of dictionary lookups. Even if the module name has gone out of scope, 334the module is probably available in :data:`sys.modules`. 335 336 337Why are default values shared between objects? 338---------------------------------------------- 339 340This 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 347The first time you call this function, ``mydict`` contains a single item. The 348second time, ``mydict`` contains two items because when ``foo()`` begins 349executing, ``mydict`` starts out with an item already in it. 350 351It is often expected that a function call creates new objects for default 352values. This is not what happens. Default values are created exactly once, when 353the function is defined. If that object is changed, like the dictionary in this 354example, subsequent calls to the function will refer to this changed object. 355 356By definition, immutable objects such as numbers, strings, tuples, and ``None``, 357are safe from change. Changes to mutable objects such as dictionaries, lists, 358and class instances can lead to confusion. 359 360Because of this feature, it is good programming practice to not use mutable 361objects as default values. Instead, use ``None`` as the default value and 362inside the function, check if the parameter is ``None`` and create a new 363list/dictionary/whatever if it is. For example, don't write:: 364 365 def foo(mydict={}): 366 ... 367 368but:: 369 370 def foo(mydict=None): 371 if mydict is None: 372 mydict = {} # create a new dict for local namespace 373 374This feature can be useful. When you have a function that's time-consuming to 375compute, a common technique is to cache the parameters and the resulting value 376of each call to the function, and return the cached value if the same value is 377requested 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 389You could use a global variable containing a dictionary instead of the default 390value; it's a matter of taste. 391 392 393How can I pass optional or keyword parameters from one function to another? 394--------------------------------------------------------------------------- 395 396Collect the arguments using the ``*`` and ``**`` specifiers in the function's 397parameter list; this gives you the positional arguments as a tuple and the 398keyword arguments as a dictionary. You can then pass these arguments when 399calling 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 414What is the difference between arguments and parameters? 415-------------------------------------------------------- 416 417:term:`Parameters <parameter>` are defined by the names that appear in a 418function definition, whereas :term:`arguments <argument>` are the values 419actually passed to a function when calling it. Parameters define what 420:term:`kind of arguments <parameter>` a function can accept. For 421example, 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 431the values ``42``, ``314``, and ``somevar`` are arguments. 432 433 434Why did changing list 'y' also change list 'x'? 435------------------------------------------------ 436 437If you wrote code like:: 438 439 >>> x = [] 440 >>> y = x 441 >>> y.append(10) 442 >>> y 443 [10] 444 >>> x 445 [10] 446 447you might be wondering why appending an element to ``y`` changed ``x`` too. 448 449There are two factors that produce this result: 450 4511) 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. 4552) Lists are :term:`mutable`, which means that you can change their content. 456 457After the call to :meth:`!append`, the content of the mutable object has 458changed from ``[]`` to ``[10]``. Since both the variables refer to the same 459object, using either name accesses the modified value ``[10]``. 460 461If 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 471we can see that in this case ``x`` and ``y`` are not equal anymore. This is 472because integers are :term:`immutable`, and when we do ``x = x + 1`` we are not 473mutating the int ``5`` by incrementing its value; instead, we are creating a 474new object (the int ``6``) and assigning it to ``x`` (that is, changing which 475object ``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 479Some operations (for example ``y.append(10)`` and ``y.sort()``) mutate the 480object, whereas superficially similar operations (for example ``y = y + [10]`` 481and :func:`sorted(y) <sorted>`) create a new object. In general in Python (and in all cases 482in the standard library) a method that mutates an object will return ``None`` 483to help avoid getting the two types of operations confused. So if you 484mistakenly write ``y.sort()`` thinking it will give you a sorted copy of ``y``, 485you'll instead end up with ``None``, which will likely cause your program to 486generate an easily diagnosed error. 487 488However, there is one class of operations where the same operation sometimes 489has different behaviors with different types: the augmented assignment 490operators. 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 493new objects). 494 495In 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 505If you want to know if two variables refer to the same object or not, you can 506use the :keyword:`is` operator, or the built-in function :func:`id`. 507 508 509How do I write a function with output parameters (call by reference)? 510--------------------------------------------------------------------- 511 512Remember that arguments are passed by assignment in Python. Since assignment 513just creates references to objects, there's no alias between an argument name in 514the caller and callee, and so no call-by-reference per se. You can achieve the 515desired effect in a number of ways. 516 5171) 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 5302) By using global variables. This isn't thread-safe, and is not recommended. 531 5323) 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 5434) 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 5545) 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 573Your best choice is to return a tuple containing the multiple results. 574 575 576How do you make a higher order function in Python? 577-------------------------------------------------- 578 579You have two choices: you can use nested scopes or you can use callable objects. 580For example, suppose you wanted to define ``linear(a,b)`` which returns a 581function ``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 588Or 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 598In both cases, :: 599 600 taxes = linear(0.3, 2) 601 602gives a callable object where ``taxes(10e6) == 0.3 * 10e6 + 2``. 603 604The callable object approach has the disadvantage that it is a bit slower and 605results in slightly longer code. However, note that a collection of callables 606can 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 613Object 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 631Here ``inc()``, ``dec()`` and ``reset()`` act like functions which share the 632same counting variable. 633 634 635How do I copy an object in Python? 636---------------------------------- 637 638In general, try :func:`copy.copy` or :func:`copy.deepcopy` for the general case. 639Not all objects can be copied, but most can. 640 641Some objects can be copied more easily. Dictionaries have a :meth:`~dict.copy` 642method:: 643 644 newdict = olddict.copy() 645 646Sequences can be copied by slicing:: 647 648 new_l = l[:] 649 650 651How can I find the methods or attributes of an object? 652------------------------------------------------------ 653 654For an instance ``x`` of a user-defined class, :func:`dir(x) <dir>` returns an alphabetized 655list of the names containing the instance attributes and methods and attributes 656defined by its class. 657 658 659How can my code discover the name of an object? 660----------------------------------------------- 661 662Generally speaking, it can't, because objects don't really have names. 663Essentially, 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 665callable. 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 678Arguably the class has a name: even though it is bound to two names and invoked 679through the name ``B`` the created instance is still reported as an instance of 680class ``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 683Generally speaking it should not be necessary for your code to "know the names" 684of particular values. Unless you are deliberately writing introspective 685programs, this is usually an indication that a change of approach might be 686beneficial. 687 688In comp.lang.python, Fredrik Lundh once gave an excellent analogy in answer to 689this 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 700What's up with the comma operator's precedence? 701----------------------------------------------- 702 703Comma is not an operator in Python. Consider this session:: 704 705 >>> "a" in "b", "a" 706 (False, 'a') 707 708Since the comma is not an operator, but a separator between expressions the 709above is evaluated as if you had entered:: 710 711 ("a" in "b"), "a" 712 713not:: 714 715 "a" in ("b", "a") 716 717The same is true of the various assignment operators (``=``, ``+=`` etc). They 718are not truly operators but syntactic delimiters in assignment statements. 719 720 721Is there an equivalent of C's "?:" ternary operator? 722---------------------------------------------------- 723 724Yes, 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 731Before this syntax was introduced in Python 2.5, a common idiom was to use 732logical operators:: 733 734 [expression] and [on_true] or [on_false] 735 736However, this idiom is unsafe, as it can give wrong results when *on_true* 737has a false boolean value. Therefore, it is always better to use 738the ``... if ... else ...`` form. 739 740 741Is it possible to write obfuscated one-liners in Python? 742-------------------------------------------------------- 743 744Yes. 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 771Don't try this at home, kids! 772 773 774.. _faq-positional-only-arguments: 775 776What does the slash(/) in the parameter list of a function mean? 777---------------------------------------------------------------- 778 779A slash in the argument list of a function denotes that the parameters prior to 780it are positional-only. Positional-only parameters are the ones without an 781externally usable name. Upon calling a function that accepts positional-only 782parameters, arguments are mapped to parameters based solely on their position. 783For example, :func:`divmod` is a function that accepts positional-only 784parameters. 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 792The slash at the end of the parameter list means that both parameters are 793positional-only. Thus, calling :func:`divmod` with keyword arguments would lead 794to 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 802Numbers and strings 803=================== 804 805How do I specify hexadecimal and octal integers? 806------------------------------------------------ 807 808To specify an octal digit, precede the octal value with a zero, and then a lower 809or 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 816Hexadecimal is just as easy. Simply precede the hexadecimal number with a zero, 817and then a lower or uppercase "x". Hexadecimal digits can be specified in lower 818or uppercase. For example, in the Python interpreter:: 819 820 >>> a = 0xa5 821 >>> a 822 165 823 >>> b = 0XB2 824 >>> b 825 178 826 827 828Why does -22 // 10 return -3? 829----------------------------- 830 831It's primarily driven by the desire that ``i % j`` have the same sign as ``j``. 832If you want that, and also want:: 833 834 i == (i // j) * j + (i % j) 835 836then integer division has to return the floor. C also requires that identity to 837hold, and then compilers that truncate ``i // j`` need to make ``i % j`` have 838the same sign as ``i``. 839 840There are few real use cases for ``i % j`` when ``j`` is negative. When ``j`` 841is 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 843ago? ``-190 % 12 == 2`` is useful; ``-190 % 12 == -10`` is a bug waiting to 844bite. 845 846 847How do I get int literal attribute instead of SyntaxError? 848---------------------------------------------------------- 849 850Trying to lookup an ``int`` literal attribute in the normal manner gives 851a :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 859The solution is to separate the literal from the period 860with either a space or parentheses. 861 862 >>> 1 .__class__ 863 <class 'int'> 864 >>> (1).__class__ 865 <class 'int'> 866 867 868How do I convert a string to a number? 869-------------------------------------- 870 871For integers, use the built-in :func:`int` type constructor, e.g. ``int('144') 872== 144``. Similarly, :func:`float` converts to a floating-point number, 873e.g. ``float('144') == 144.0``. 874 875By default, these interpret the number as decimal, so that ``int('0144') == 876144`` holds true, and ``int('0x144')`` raises :exc:`ValueError`. ``int(string, 877base)`` 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 879using Python's rules: a leading '0o' indicates octal, and '0x' indicates a hex 880number. 881 882Do not use the built-in function :func:`eval` if all you need is to convert 883strings to numbers. :func:`eval` will be significantly slower and it presents a 884security risk: someone could pass you a Python expression that might have 885unwanted side effects. For example, someone could pass 886``__import__('os').system("rm -rf $HOME")`` which would erase your home 887directory. 888 889:func:`eval` also has the effect of interpreting numbers as Python expressions, 890so that e.g. ``eval('09')`` gives a syntax error because Python does not allow 891leading '0' in a decimal number (except '0'). 892 893 894How do I convert a number to a string? 895-------------------------------------- 896 897To convert, e.g., the number ``144`` to the string ``'144'``, use the built-in type 898constructor :func:`str`. If you want a hexadecimal or octal representation, use 899the built-in functions :func:`hex` or :func:`oct`. For fancy formatting, see 900the :ref:`f-strings` and :ref:`formatstrings` sections, 901e.g. ``"{:04d}".format(144)`` yields 902``'0144'`` and ``"{:.3f}".format(1.0/3.0)`` yields ``'0.333'``. 903 904 905How do I modify a string in place? 906---------------------------------- 907 908You can't, because strings are immutable. In most situations, you should 909simply construct a new string from the various parts you want to assemble 910it from. However, if you need an object with the ability to modify in-place 911unicode data, try using an :class:`io.StringIO` object or the :mod:`array` 912module:: 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 937How do I use strings to call functions/methods? 938----------------------------------------------- 939 940There 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 989Is there an equivalent to Perl's chomp() for removing trailing newlines from strings? 990------------------------------------------------------------------------------------- 991 992You can use ``S.rstrip("\r\n")`` to remove all occurrences of any line 993terminator from the end of the string ``S`` without removing other trailing 994whitespace. If the string ``S`` represents more than one line, with several 995empty lines at the end, the line terminators for all the blank lines will 996be removed:: 997 998 >>> lines = ("line 1 \r\n" 999 ... "\r\n" 1000 ... "\r\n") 1001 >>> lines.rstrip("\n\r") 1002 'line 1 ' 1003 1004Since this is typically only desired when reading text one line at a time, using 1005``S.rstrip()`` this way works well. 1006 1007 1008Is there a scanf() or sscanf() equivalent? 1009------------------------------------------ 1010 1011Not as such. 1012 1013For simple input parsing, the easiest approach is usually to split the line into 1014whitespace-delimited words using the :meth:`~str.split` method of string objects 1015and then convert decimal strings to numeric values using :func:`int` or 1016:func:`float`. :meth:`!split` supports an optional "sep" parameter which is useful 1017if the line uses something other than whitespace as a separator. 1018 1019For more complicated input parsing, regular expressions are more powerful 1020than C's ``sscanf`` and better suited for the task. 1021 1022 1023What does 'UnicodeDecodeError' or 'UnicodeEncodeError' error mean? 1024------------------------------------------------------------------- 1025 1026See the :ref:`unicode-howto`. 1027 1028 1029.. _faq-programming-raw-string-backslash: 1030 1031Can I end a raw string with an odd number of backslashes? 1032--------------------------------------------------------- 1033 1034A 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 1042There are several workarounds for this. One is to use regular strings and double 1043the backslashes:: 1044 1045 >>> 'C:\\this\\will\\work\\' 1046 'C:\\this\\will\\work\\' 1047 1048Another is to concatenate a regular string containing an escaped backslash to the 1049raw string:: 1050 1051 >>> r'C:\this\will\work' '\\' 1052 'C:\\this\\will\\work\\' 1053 1054It 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 1059Note that while a backslash will "escape" a quote for the purposes of 1060determining where the raw string ends, no escaping occurs when interpreting the 1061value of the raw string. That is, the backslash remains present in the value of 1062the raw string:: 1063 1064 >>> r'backslash\'preserved' 1065 "backslash\\'preserved" 1066 1067Also see the specification in the :ref:`language reference <strings>`. 1068 1069Performance 1070=========== 1071 1072My program is too slow. How do I speed it up? 1073--------------------------------------------- 1074 1075That's a tough one, in general. First, here are a list of things to 1076remember 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 1090That being said, there are many tricks to speed up Python code. Here are 1091some general principles which go a long way towards reaching acceptable 1092performance 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 1115If you have reached the limit of what pure Python can allow, there are tools 1116to take you further away. For example, `Cython <https://cython.org>`_ can 1117compile a slightly modified version of Python code into a C extension, and 1118can be used on many different platforms. Cython can take advantage of 1119compilation (and optional type annotations) to make your code significantly 1120faster than when interpreted. If you are confident in your C programming 1121skills, you can also :ref:`write a C extension module <extending-index>` 1122yourself. 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 1130What is the most efficient way to concatenate many strings together? 1131-------------------------------------------------------------------- 1132 1133:class:`str` and :class:`bytes` objects are immutable, therefore concatenating 1134many strings together is inefficient as each concatenation creates a new 1135object. In the general case, the total runtime cost is quadratic in the 1136total string length. 1137 1138To accumulate many :class:`str` objects, the recommended idiom is to place 1139them 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 1148To accumulate many :class:`bytes` objects, the recommended idiom is to extend 1149a :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 1156Sequences (Tuples/Lists) 1157======================== 1158 1159How do I convert between tuples and lists? 1160------------------------------------------ 1161 1162The type constructor ``tuple(seq)`` converts any sequence (actually, any 1163iterable) into a tuple with the same items in the same order. 1164 1165For example, ``tuple([1, 2, 3])`` yields ``(1, 2, 3)`` and ``tuple('abc')`` 1166yields ``('a', 'b', 'c')``. If the argument is a tuple, it does not make a copy 1167but returns the same object, so it is cheap to call :func:`tuple` when you 1168aren't sure that an object is already a tuple. 1169 1170The type constructor ``list(seq)`` converts any sequence or iterable into a list 1171with 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 1173is a list, it makes a copy just like ``seq[:]`` would. 1174 1175 1176What's a negative index? 1177------------------------ 1178 1179Python sequences are indexed with positive numbers and negative numbers. For 1180positive numbers 0 is the first index 1 is the second index and so forth. For 1181negative indices -1 is the last index and -2 is the penultimate (next to last) 1182index and so forth. Think of ``seq[-n]`` as the same as ``seq[len(seq)-n]``. 1183 1184Using negative indices can be very convenient. For example ``S[:-1]`` is all of 1185the string except for its last character, which is useful for removing the 1186trailing newline from a string. 1187 1188 1189How do I iterate over a sequence in reverse order? 1190-------------------------------------------------- 1191 1192Use the :func:`reversed` built-in function:: 1193 1194 for x in reversed(sequence): 1195 ... # do something with x ... 1196 1197This won't touch your original sequence, but build a new copy with reversed 1198order to iterate over. 1199 1200 1201How do you remove duplicates from a list? 1202----------------------------------------- 1203 1204See the Python Cookbook for a long discussion of many ways to do this: 1205 1206 https://code.activestate.com/recipes/52560/ 1207 1208If you don't mind reordering the list, sort it and then scan from the end of the 1209list, 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 1220If 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 1225This converts the list into a set, thereby removing duplicates, and then back 1226into a list. 1227 1228 1229How do you remove multiple items from a list 1230-------------------------------------------- 1231 1232As with removing duplicates, explicitly iterating in reverse with a 1233delete condition is one possibility. However, it is easier and faster 1234to use slice replacement with an implicit or explicit forward iteration. 1235Here 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 1241The list comprehension may be fastest. 1242 1243 1244How do you make an array in Python? 1245----------------------------------- 1246 1247Use a list:: 1248 1249 ["this", 1, "is", "an", "array"] 1250 1251Lists are equivalent to C or Pascal arrays in their time complexity; the primary 1252difference is that a Python list can contain objects of many different types. 1253 1254The ``array`` module also provides methods for creating arrays of fixed types 1255with compact representations, but they are slower to index than lists. Also 1256note that `NumPy <https://numpy.org/>`_ 1257and other third party packages define array-like structures with 1258various characteristics as well. 1259 1260To get Lisp-style linked lists, you can emulate *cons cells* using tuples:: 1261 1262 lisp_list = ("like", ("this", ("example", None) ) ) 1263 1264If mutability is desired, you could use lists instead of tuples. Here the 1265analogue 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 1267usually a lot slower than using Python lists. 1268 1269 1270.. _faq-multidimensional-list: 1271 1272How do I create a multidimensional list? 1273---------------------------------------- 1274 1275You probably tried to make a multidimensional array like this:: 1276 1277 >>> A = [[None] * 2] * 3 1278 1279This 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 1290But 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 1302The reason is that replicating a list with ``*`` doesn't create copies, it only 1303creates references to the existing objects. The ``*3`` creates a list 1304containing 3 references to the same list of length two. Changes to one row will 1305show in all rows, which is almost certainly not what you want. 1306 1307The suggested approach is to create a list of the desired length first and then 1308fill 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 1314This generates a list containing 3 different lists of length two. You can also 1315use a list comprehension:: 1316 1317 w, h = 2, 3 1318 A = [[None] * w for i in range(h)] 1319 1320Or, you can use an extension that provides a matrix datatype; `NumPy 1321<https://numpy.org/>`_ is the best known. 1322 1323 1324How do I apply a method or function to a sequence of objects? 1325------------------------------------------------------------- 1326 1327To call a method or function and accumulate the return values is a list, 1328a :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 1334To just run the method or function without saving the return values, 1335a 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 1345Why does a_tuple[i] += ['item'] raise an exception when the addition works? 1346--------------------------------------------------------------------------- 1347 1348This is because of a combination of the fact that augmented assignment 1349operators are *assignment* operators, and the difference between mutable and 1350immutable objects in Python. 1351 1352This discussion applies in general when augmented assignment operators are 1353applied to elements of a tuple that point to mutable objects, but we'll use 1354a ``list`` and ``+=`` as our exemplar. 1355 1356If 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 1364The reason for the exception should be immediately clear: ``1`` is added to the 1365object ``a_tuple[0]`` points to (``1``), producing the result object, ``2``, 1366but 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 1368a tuple points to. 1369 1370Under the covers, what this augmented assignment statement is doing is 1371approximately 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 1379It is the assignment part of the operation that produces the error, since a 1380tuple is immutable. 1381 1382When 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 1390The exception is a bit more surprising, and even more surprising is the fact 1391that even though there was an error, the append worked:: 1392 1393 >>> a_tuple[0] 1394 ['foo', 'item'] 1395 1396To 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 1398assignment 1399is executed, and its return value is what gets used in the assignment statement; 1400and (b) for lists, :meth:`!__iadd__` is equivalent to calling :meth:`!extend` on the list 1401and returning the list. That's why we say that for lists, ``+=`` is a 1402"shorthand" for :meth:`!list.extend`:: 1403 1404 >>> a_list = [] 1405 >>> a_list += [1] 1406 >>> a_list 1407 [1] 1408 1409This is equivalent to:: 1410 1411 >>> result = a_list.__iadd__([1]) 1412 >>> a_list = result 1413 1414The object pointed to by a_list has been mutated, and the pointer to the 1415mutated object is assigned back to ``a_list``. The end result of the 1416assignment is a no-op, since it is a pointer to the same object that ``a_list`` 1417was previously pointing to, but the assignment still happens. 1418 1419Thus, 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 1427The :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, 1429that final assignment still results in an error, because tuples are immutable. 1430 1431 1432I want to do a complicated sort: can you do a Schwartzian Transform in Python? 1433------------------------------------------------------------------------------ 1434 1435The technique, attributed to Randal Schwartz of the Perl community, sorts the 1436elements of a list by a metric which maps each element to its "sort value". In 1437Python, 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 1443How can I sort one list by values from another list? 1444---------------------------------------------------- 1445 1446Merge them into an iterator of tuples, sort the resulting list, and then pick 1447out 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 1460Objects 1461======= 1462 1463What is a class? 1464---------------- 1465 1466A class is the particular object type created by executing a class statement. 1467Class objects are used as templates to create instance objects, which embody 1468both the data (attributes) and code (methods) specific to a datatype. 1469 1470A class can be based on one or more other classes, called its base class(es). It 1471then inherits the attributes and methods of its base classes. This allows an 1472object model to be successively refined by inheritance. You might have a 1473generic ``Mailbox`` class that provides basic accessor methods for a mailbox, 1474and subclasses such as ``MboxMailbox``, ``MaildirMailbox``, ``OutlookMailbox`` 1475that handle various specific mailbox formats. 1476 1477 1478What is a method? 1479----------------- 1480 1481A 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 1483definition:: 1484 1485 class C: 1486 def meth(self, arg): 1487 return arg * 2 + self.attribute 1488 1489 1490What is self? 1491------------- 1492 1493Self is merely a conventional name for the first argument of a method. A method 1494defined as ``meth(self, a, b, c)`` should be called as ``x.meth(a, b, c)`` for 1495some instance ``x`` of the class in which the definition occurs; the called 1496method will think it is called as ``meth(x, a, b, c)``. 1497 1498See also :ref:`why-self`. 1499 1500 1501How do I check if an object is an instance of a given class or of a subclass of it? 1502----------------------------------------------------------------------------------- 1503 1504Use the built-in function :func:`isinstance(obj, cls) <isinstance>`. You can 1505check if an object 1506is an instance of any of a number of classes by providing a tuple instead of a 1507single class, e.g. ``isinstance(obj, (class1, class2, ...))``, and can also 1508check whether an object is one of Python's built-in types, e.g. 1509``isinstance(obj, str)`` or ``isinstance(obj, (int, float, complex))``. 1510 1511Note that :func:`isinstance` also checks for virtual inheritance from an 1512:term:`abstract base class`. So, the test will return ``True`` for a 1513registered class even if hasn't directly or indirectly inherited from it. To 1514test 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 1546Note that most programs do not use :func:`isinstance` on user-defined classes 1547very often. If you are developing the classes yourself, a more proper 1548object-oriented style is to define methods on the classes that encapsulate a 1549particular behaviour, instead of checking the object's class and doing a 1550different thing based on what class it is. For example, if you have a function 1551that 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 1560A better approach is to define a ``search()`` method on all the classes and just 1561call 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 1574What is delegation? 1575------------------- 1576 1577Delegation is an object oriented technique (also called a design pattern). 1578Let's say you have an object ``x`` and want to change the behaviour of just one 1579of its methods. You can create a new class that provides a new implementation 1580of the method you're interested in changing and delegates all other methods to 1581the corresponding method of ``x``. 1582 1583Python programmers can easily implement delegation. For example, the following 1584class implements a class that behaves like a file but converts all written data 1585to 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 1598Here the ``UpperOut`` class redefines the ``write()`` method to convert the 1599argument string to uppercase before calling the underlying 1600``self._outfile.write()`` method. All other methods are delegated to the 1601underlying ``self._outfile`` object. The delegation is accomplished via the 1602:meth:`~object.__getattr__` method; consult :ref:`the language reference <attribute-access>` 1603for more information about controlling attribute access. 1604 1605Note that for more general cases delegation can get trickier. When attributes 1606must be set as well as retrieved, the class must define a :meth:`~object.__setattr__` 1607method 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 1616Many :meth:`~object.__setattr__` implementations call :meth:`!object.__setattr__` to set 1617an 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 1624Alternatively, it is possible to set attributes by inserting 1625entries into :attr:`self.__dict__ <object.__dict__>` directly. 1626 1627 1628How do I call a method defined in a base class from a derived class that extends it? 1629------------------------------------------------------------------------------------ 1630 1631Use the built-in :func:`super` function:: 1632 1633 class Derived(Base): 1634 def meth(self): 1635 super().meth() # calls Base.meth 1636 1637In the example, :func:`super` will automatically determine the instance from 1638which it was called (the ``self`` value), look up the :term:`method resolution 1639order` (MRO) with ``type(self).__mro__``, and return the next in line after 1640``Derived`` in the MRO: ``Base``. 1641 1642 1643How can I organize my code to make it easier to change the base class? 1644---------------------------------------------------------------------- 1645 1646You could assign the base class to an alias and derive from the alias. Then all 1647you have to change is the value assigned to the alias. Incidentally, this trick 1648is also handy if you want to decide dynamically (e.g. depending on availability 1649of resources) which base class to use. Example:: 1650 1651 class Base: 1652 ... 1653 1654 BaseAlias = Base 1655 1656 class Derived(BaseAlias): 1657 ... 1658 1659 1660How do I create static class data and static class methods? 1661----------------------------------------------------------- 1662 1663Both static data and static methods (in the sense of C++ or Java) are supported 1664in Python. 1665 1666For static data, simply define a class attribute. To assign a new value to the 1667attribute, 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, 1679C)`` holds, unless overridden by ``c`` itself or by some class on the base-class 1680search path from ``c.__class__`` back to ``C``. 1681 1682Caution: within a method of C, an assignment like ``self.count = 42`` creates a 1683new and unrelated instance named "count" in ``self``'s own dict. Rebinding of a 1684class-static data name must always specify the class whether inside a method or 1685not:: 1686 1687 C.count = 314 1688 1689Static methods are possible:: 1690 1691 class C: 1692 @staticmethod 1693 def static(arg1, arg2, arg3): 1694 # No 'self' parameter! 1695 ... 1696 1697However, a far more straightforward way to get the effect of a static method is 1698via a simple module-level function:: 1699 1700 def getcount(): 1701 return C.count 1702 1703If your code is structured so as to define one class (or tightly related class 1704hierarchy) per module, this supplies the desired encapsulation. 1705 1706 1707How can I overload constructors (or methods) in Python? 1708------------------------------------------------------- 1709 1710This answer actually applies to all methods, but the question usually comes up 1711first in the context of constructors. 1712 1713In 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 1722In Python you have to write a single constructor that catches all cases using 1723default 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 1732This is not entirely equivalent, but close enough in practice. 1733 1734You could also try a variable-length argument list, e.g. :: 1735 1736 def __init__(self, *args): 1737 ... 1738 1739The same approach works for all method definitions. 1740 1741 1742I try to use __spam and I get an error about _SomeClassName__spam. 1743------------------------------------------------------------------ 1744 1745Variable names with double leading underscores are "mangled" to provide a simple 1746but effective way to define class private variables. Any identifier of the form 1747``__spam`` (at least two leading underscores, at most one trailing underscore) 1748is textually replaced with ``_classname__spam``, where ``classname`` is the 1749current class name with any leading underscores stripped. 1750 1751The identifier can be used unchanged within the class, but to access it outside 1752the 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 1768In particular, this does not guarantee privacy since an outside user can still 1769deliberately access the private attribute; many Python programmers never bother 1770to 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 1777My class defines __del__ but it is not called when I delete the object. 1778----------------------------------------------------------------------- 1779 1780There are several possible reasons for this. 1781 1782The :keyword:`del` statement does not necessarily call :meth:`~object.__del__` -- it simply 1783decrements the object's reference count, and if this reaches zero 1784:meth:`!__del__` is called. 1785 1786If your data structures contain circular links (e.g. a tree where each child has 1787a parent reference and each parent has a list of children) the reference counts 1788will never go back to zero. Once in a while Python runs an algorithm to detect 1789such cycles, but the garbage collector might run some time after the last 1790reference to your data structure vanishes, so your :meth:`!__del__` method may be 1791called at an inconvenient and random time. This is inconvenient if you're trying 1792to reproduce a problem. Worse, the order in which object's :meth:`!__del__` 1793methods are executed is arbitrary. You can run :func:`gc.collect` to force a 1794collection, but there *are* pathological cases where objects will never be 1795collected. 1796 1797Despite 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 1800call :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 1802object. 1803 1804Another way to avoid cyclical references is to use the :mod:`weakref` module, 1805which allows you to point to objects without incrementing their reference count. 1806Tree data structures, for instance, should use weak references for their parent 1807and 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 1817Finally, if your :meth:`!__del__` method raises an exception, a warning message 1818is printed to :data:`sys.stderr`. 1819 1820 1821How do I get a list of all instances of a given class? 1822------------------------------------------------------ 1823 1824Python does not keep track of all instances of a class (or of a built-in type). 1825You can program the class's constructor to keep track of all instances by 1826keeping a list of weak references to each instance. 1827 1828 1829Why does the result of ``id()`` appear to be not unique? 1830-------------------------------------------------------- 1831 1832The :func:`id` builtin returns an integer that is guaranteed to be unique during 1833the lifetime of the object. Since in CPython, this is the object's memory 1834address, it happens frequently that after an object is deleted from memory, the 1835next freshly created object is allocated at the same position in memory. This 1836is illustrated by this example: 1837 1838>>> id(1000) # doctest: +SKIP 183913901272 1840>>> id(2000) # doctest: +SKIP 184113901272 1842 1843The two ids belong to different integer objects that are created before, and 1844deleted immediately after execution of the ``id()`` call. To be sure that 1845objects whose id you want to examine are still alive, create another reference 1846to the object: 1847 1848>>> a = 1000; b = 2000 1849>>> id(a) # doctest: +SKIP 185013901272 1851>>> id(b) # doctest: +SKIP 185213891296 1853 1854 1855When can I rely on identity tests with the *is* operator? 1856--------------------------------------------------------- 1857 1858The ``is`` operator tests for object identity. The test ``a is b`` is 1859equivalent to ``id(a) == id(b)``. 1860 1861The most important property of an identity test is that an object is always 1862identical to itself, ``a is a`` always returns ``True``. Identity tests are 1863usually faster than equality tests. And unlike equality tests, identity tests 1864are guaranteed to return a boolean ``True`` or ``False``. 1865 1866However, identity tests can *only* be substituted for equality tests when 1867object identity is assured. Generally, there are three circumstances where 1868identity is guaranteed: 1869 18701) Assignments create new names but do not change object identity. After the 1871assignment ``new = old``, it is guaranteed that ``new is old``. 1872 18732) Putting an object in a container that stores object references does not 1874change object identity. After the list assignment ``s[0] = x``, it is 1875guaranteed that ``s[0] is x``. 1876 18773) If an object is a singleton, it means that only one instance of that object 1878can exist. After the assignments ``a = None`` and ``b = None``, it is 1879guaranteed that ``a is b`` because ``None`` is a singleton. 1880 1881In most other circumstances, identity tests are inadvisable and equality tests 1882are preferred. In particular, identity tests should not be used to check 1883constants such as :class:`int` and :class:`str` which aren't guaranteed to be 1884singletons:: 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 1898Likewise, new instances of mutable containers are never identical:: 1899 1900 >>> a = [] 1901 >>> b = [] 1902 >>> a is b 1903 False 1904 1905In the standard library code, you will see several common patterns for 1906correctly using identity tests: 1907 19081) As recommended by :pep:`8`, an identity test is the preferred way to check 1909for ``None``. This reads like plain English in code and avoids confusion with 1910other objects that may have boolean values that evaluate to false. 1911 19122) Detecting optional arguments can be tricky when ``None`` is a valid input 1913value. In those situations, you can create a singleton sentinel object 1914guaranteed to be distinct from other objects. For example, here is how 1915to implement a method that behaves like :meth:`dict.pop`:: 1916 1917 _sentinel = object() 1918 1919 def pop(self, key, default=_sentinel): 1920 if key in self: 1921 value = self[key] 1922 del self[key] 1923 return value 1924 if default is _sentinel: 1925 raise KeyError(key) 1926 return default 1927 19283) Container implementations sometimes need to augment equality tests with 1929identity tests. This prevents the code from being confused by objects such as 1930``float('NaN')`` that are not equal to themselves. 1931 1932For example, here is the implementation of 1933:meth:`!collections.abc.Sequence.__contains__`:: 1934 1935 def __contains__(self, value): 1936 for v in self: 1937 if v is value or v == value: 1938 return True 1939 return False 1940 1941 1942How can a subclass control what data is stored in an immutable instance? 1943------------------------------------------------------------------------ 1944 1945When subclassing an immutable type, override the :meth:`~object.__new__` method 1946instead of the :meth:`~object.__init__` method. The latter only runs *after* an 1947instance is created, which is too late to alter data in an immutable 1948instance. 1949 1950All of these immutable classes have a different signature than their 1951parent class: 1952 1953.. testcode:: 1954 1955 from datetime import date 1956 1957 class FirstOfMonthDate(date): 1958 "Always choose the first day of the month" 1959 def __new__(cls, year, month, day): 1960 return super().__new__(cls, year, month, 1) 1961 1962 class NamedInt(int): 1963 "Allow text names for some numbers" 1964 xlat = {'zero': 0, 'one': 1, 'ten': 10} 1965 def __new__(cls, value): 1966 value = cls.xlat.get(value, value) 1967 return super().__new__(cls, value) 1968 1969 class TitleStr(str): 1970 "Convert str to name suitable for a URL path" 1971 def __new__(cls, s): 1972 s = s.lower().replace(' ', '-') 1973 s = ''.join([c for c in s if c.isalnum() or c == '-']) 1974 return super().__new__(cls, s) 1975 1976The classes can be used like this: 1977 1978.. doctest:: 1979 1980 >>> FirstOfMonthDate(2012, 2, 14) 1981 FirstOfMonthDate(2012, 2, 1) 1982 >>> NamedInt('ten') 1983 10 1984 >>> NamedInt(20) 1985 20 1986 >>> TitleStr('Blog: Why Python Rocks') 1987 'blog-why-python-rocks' 1988 1989 1990.. _faq-cache-method-calls: 1991 1992How do I cache method calls? 1993---------------------------- 1994 1995The two principal tools for caching methods are 1996:func:`functools.cached_property` and :func:`functools.lru_cache`. The 1997former stores results at the instance level and the latter at the class 1998level. 1999 2000The *cached_property* approach only works with methods that do not take 2001any arguments. It does not create a reference to the instance. The 2002cached method result will be kept only as long as the instance is alive. 2003 2004The advantage is that when an instance is no longer used, the cached 2005method result will be released right away. The disadvantage is that if 2006instances accumulate, so too will the accumulated method results. They 2007can grow without bound. 2008 2009The *lru_cache* approach works with methods that have :term:`hashable` 2010arguments. It creates a reference to the instance unless special 2011efforts are made to pass in weak references. 2012 2013The advantage of the least recently used algorithm is that the cache is 2014bounded by the specified *maxsize*. The disadvantage is that instances 2015are kept alive until they age out of the cache or until the cache is 2016cleared. 2017 2018This example shows the various techniques:: 2019 2020 class Weather: 2021 "Lookup weather information on a government website" 2022 2023 def __init__(self, station_id): 2024 self._station_id = station_id 2025 # The _station_id is private and immutable 2026 2027 def current_temperature(self): 2028 "Latest hourly observation" 2029 # Do not cache this because old results 2030 # can be out of date. 2031 2032 @cached_property 2033 def location(self): 2034 "Return the longitude/latitude coordinates of the station" 2035 # Result only depends on the station_id 2036 2037 @lru_cache(maxsize=20) 2038 def historic_rainfall(self, date, units='mm'): 2039 "Rainfall on a given date" 2040 # Depends on the station_id, date, and units. 2041 2042The above example assumes that the *station_id* never changes. If the 2043relevant instance attributes are mutable, the *cached_property* approach 2044can't be made to work because it cannot detect changes to the 2045attributes. 2046 2047To make the *lru_cache* approach work when the *station_id* is mutable, 2048the class needs to define the :meth:`~object.__eq__` and :meth:`~object.__hash__` 2049methods so that the cache can detect relevant attribute updates:: 2050 2051 class Weather: 2052 "Example with a mutable station identifier" 2053 2054 def __init__(self, station_id): 2055 self.station_id = station_id 2056 2057 def change_station(self, station_id): 2058 self.station_id = station_id 2059 2060 def __eq__(self, other): 2061 return self.station_id == other.station_id 2062 2063 def __hash__(self): 2064 return hash(self.station_id) 2065 2066 @lru_cache(maxsize=20) 2067 def historic_rainfall(self, date, units='cm'): 2068 'Rainfall on a given date' 2069 # Depends on the station_id, date, and units. 2070 2071 2072Modules 2073======= 2074 2075How do I create a .pyc file? 2076---------------------------- 2077 2078When a module is imported for the first time (or when the source file has 2079changed since the current compiled file was created) a ``.pyc`` file containing 2080the compiled code should be created in a ``__pycache__`` subdirectory of the 2081directory containing the ``.py`` file. The ``.pyc`` file will have a 2082filename that starts with the same name as the ``.py`` file, and ends with 2083``.pyc``, with a middle component that depends on the particular ``python`` 2084binary that created it. (See :pep:`3147` for details.) 2085 2086One reason that a ``.pyc`` file may not be created is a permissions problem 2087with the directory containing the source file, meaning that the ``__pycache__`` 2088subdirectory cannot be created. This can happen, for example, if you develop as 2089one user but run as another, such as if you are testing with a web server. 2090 2091Unless the :envvar:`PYTHONDONTWRITEBYTECODE` environment variable is set, 2092creation of a .pyc file is automatic if you're importing a module and Python 2093has the ability (permissions, free space, etc...) to create a ``__pycache__`` 2094subdirectory and write the compiled module to that subdirectory. 2095 2096Running Python on a top level script is not considered an import and no 2097``.pyc`` will be created. For example, if you have a top-level module 2098``foo.py`` that imports another module ``xyz.py``, when you run ``foo`` (by 2099typing ``python foo.py`` as a shell command), a ``.pyc`` will be created for 2100``xyz`` because ``xyz`` is imported, but no ``.pyc`` file will be created for 2101``foo`` since ``foo.py`` isn't being imported. 2102 2103If you need to create a ``.pyc`` file for ``foo`` -- that is, to create a 2104``.pyc`` file for a module that is not imported -- you can, using the 2105:mod:`py_compile` and :mod:`compileall` modules. 2106 2107The :mod:`py_compile` module can manually compile any module. One way is to use 2108the ``compile()`` function in that module interactively:: 2109 2110 >>> import py_compile 2111 >>> py_compile.compile('foo.py') # doctest: +SKIP 2112 2113This will write the ``.pyc`` to a ``__pycache__`` subdirectory in the same 2114location as ``foo.py`` (or you can override that with the optional parameter 2115``cfile``). 2116 2117You can also automatically compile all files in a directory or directories using 2118the :mod:`compileall` module. You can do it from the shell prompt by running 2119``compileall.py`` and providing the path of a directory containing Python files 2120to compile:: 2121 2122 python -m compileall . 2123 2124 2125How do I find the current module name? 2126-------------------------------------- 2127 2128A module can find out its own module name by looking at the predefined global 2129variable ``__name__``. If this has the value ``'__main__'``, the program is 2130running as a script. Many modules that are usually used by importing them also 2131provide a command-line interface or a self-test, and only execute this code 2132after checking ``__name__``:: 2133 2134 def main(): 2135 print('Running test...') 2136 ... 2137 2138 if __name__ == '__main__': 2139 main() 2140 2141 2142How can I have modules that mutually import each other? 2143------------------------------------------------------- 2144 2145Suppose you have the following modules: 2146 2147:file:`foo.py`:: 2148 2149 from bar import bar_var 2150 foo_var = 1 2151 2152:file:`bar.py`:: 2153 2154 from foo import foo_var 2155 bar_var = 2 2156 2157The problem is that the interpreter will perform the following steps: 2158 2159* main imports ``foo`` 2160* Empty globals for ``foo`` are created 2161* ``foo`` is compiled and starts executing 2162* ``foo`` imports ``bar`` 2163* Empty globals for ``bar`` are created 2164* ``bar`` is compiled and starts executing 2165* ``bar`` imports ``foo`` (which is a no-op since there already is a module named ``foo``) 2166* The import mechanism tries to read ``foo_var`` from ``foo`` globals, to set ``bar.foo_var = foo.foo_var`` 2167 2168The last step fails, because Python isn't done with interpreting ``foo`` yet and 2169the global symbol dictionary for ``foo`` is still empty. 2170 2171The same thing happens when you use ``import foo``, and then try to access 2172``foo.foo_var`` in global code. 2173 2174There are (at least) three possible workarounds for this problem. 2175 2176Guido van Rossum recommends avoiding all uses of ``from <module> import ...``, 2177and placing all code inside functions. Initializations of global variables and 2178class variables should use constants or built-in functions only. This means 2179everything from an imported module is referenced as ``<module>.<name>``. 2180 2181Jim Roskind suggests performing steps in the following order in each module: 2182 2183* exports (globals, functions, and classes that don't need imported base 2184 classes) 2185* ``import`` statements 2186* active code (including globals that are initialized from imported values). 2187 2188Van Rossum doesn't like this approach much because the imports appear in a 2189strange place, but it does work. 2190 2191Matthias Urlichs recommends restructuring your code so that the recursive import 2192is not necessary in the first place. 2193 2194These solutions are not mutually exclusive. 2195 2196 2197__import__('x.y.z') returns <module 'x'>; how do I get z? 2198--------------------------------------------------------- 2199 2200Consider using the convenience function :func:`~importlib.import_module` from 2201:mod:`importlib` instead:: 2202 2203 z = importlib.import_module('x.y.z') 2204 2205 2206When I edit an imported module and reimport it, the changes don't show up. Why does this happen? 2207------------------------------------------------------------------------------------------------- 2208 2209For reasons of efficiency as well as consistency, Python only reads the module 2210file on the first time a module is imported. If it didn't, in a program 2211consisting of many modules where each one imports the same basic module, the 2212basic module would be parsed and re-parsed many times. To force re-reading of a 2213changed module, do this:: 2214 2215 import importlib 2216 import modname 2217 importlib.reload(modname) 2218 2219Warning: this technique is not 100% fool-proof. In particular, modules 2220containing statements like :: 2221 2222 from modname import some_objects 2223 2224will continue to work with the old version of the imported objects. If the 2225module contains class definitions, existing class instances will *not* be 2226updated to use the new class definition. This can result in the following 2227paradoxical behaviour:: 2228 2229 >>> import importlib 2230 >>> import cls 2231 >>> c = cls.C() # Create an instance of C 2232 >>> importlib.reload(cls) 2233 <module 'cls' from 'cls.py'> 2234 >>> isinstance(c, cls.C) # isinstance is false?!? 2235 False 2236 2237The nature of the problem is made clear if you print out the "identity" of the 2238class objects:: 2239 2240 >>> hex(id(c.__class__)) 2241 '0x7352a0' 2242 >>> hex(id(cls.C)) 2243 '0x4198d0' 2244