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:`~list.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 floating-point, 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('u', s) 928 >>> print(a) 929 array('u', 'Hello, world') 930 >>> a[0] = 'y' 931 >>> print(a) 932 array('u', '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:`~list.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 1616Most :meth:`!__setattr__` implementations must modify 1617:meth:`self.__dict__ <object.__dict__>` to store 1618local state for self without causing an infinite recursion. 1619 1620 1621How do I call a method defined in a base class from a derived class that extends it? 1622------------------------------------------------------------------------------------ 1623 1624Use the built-in :func:`super` function:: 1625 1626 class Derived(Base): 1627 def meth(self): 1628 super().meth() # calls Base.meth 1629 1630In the example, :func:`super` will automatically determine the instance from 1631which it was called (the ``self`` value), look up the :term:`method resolution 1632order` (MRO) with ``type(self).__mro__``, and return the next in line after 1633``Derived`` in the MRO: ``Base``. 1634 1635 1636How can I organize my code to make it easier to change the base class? 1637---------------------------------------------------------------------- 1638 1639You could assign the base class to an alias and derive from the alias. Then all 1640you have to change is the value assigned to the alias. Incidentally, this trick 1641is also handy if you want to decide dynamically (e.g. depending on availability 1642of resources) which base class to use. Example:: 1643 1644 class Base: 1645 ... 1646 1647 BaseAlias = Base 1648 1649 class Derived(BaseAlias): 1650 ... 1651 1652 1653How do I create static class data and static class methods? 1654----------------------------------------------------------- 1655 1656Both static data and static methods (in the sense of C++ or Java) are supported 1657in Python. 1658 1659For static data, simply define a class attribute. To assign a new value to the 1660attribute, you have to explicitly use the class name in the assignment:: 1661 1662 class C: 1663 count = 0 # number of times C.__init__ called 1664 1665 def __init__(self): 1666 C.count = C.count + 1 1667 1668 def getcount(self): 1669 return C.count # or return self.count 1670 1671``c.count`` also refers to ``C.count`` for any ``c`` such that ``isinstance(c, 1672C)`` holds, unless overridden by ``c`` itself or by some class on the base-class 1673search path from ``c.__class__`` back to ``C``. 1674 1675Caution: within a method of C, an assignment like ``self.count = 42`` creates a 1676new and unrelated instance named "count" in ``self``'s own dict. Rebinding of a 1677class-static data name must always specify the class whether inside a method or 1678not:: 1679 1680 C.count = 314 1681 1682Static methods are possible:: 1683 1684 class C: 1685 @staticmethod 1686 def static(arg1, arg2, arg3): 1687 # No 'self' parameter! 1688 ... 1689 1690However, a far more straightforward way to get the effect of a static method is 1691via a simple module-level function:: 1692 1693 def getcount(): 1694 return C.count 1695 1696If your code is structured so as to define one class (or tightly related class 1697hierarchy) per module, this supplies the desired encapsulation. 1698 1699 1700How can I overload constructors (or methods) in Python? 1701------------------------------------------------------- 1702 1703This answer actually applies to all methods, but the question usually comes up 1704first in the context of constructors. 1705 1706In C++ you'd write 1707 1708.. code-block:: c 1709 1710 class C { 1711 C() { cout << "No arguments\n"; } 1712 C(int i) { cout << "Argument is " << i << "\n"; } 1713 } 1714 1715In Python you have to write a single constructor that catches all cases using 1716default arguments. For example:: 1717 1718 class C: 1719 def __init__(self, i=None): 1720 if i is None: 1721 print("No arguments") 1722 else: 1723 print("Argument is", i) 1724 1725This is not entirely equivalent, but close enough in practice. 1726 1727You could also try a variable-length argument list, e.g. :: 1728 1729 def __init__(self, *args): 1730 ... 1731 1732The same approach works for all method definitions. 1733 1734 1735I try to use __spam and I get an error about _SomeClassName__spam. 1736------------------------------------------------------------------ 1737 1738Variable names with double leading underscores are "mangled" to provide a simple 1739but effective way to define class private variables. Any identifier of the form 1740``__spam`` (at least two leading underscores, at most one trailing underscore) 1741is textually replaced with ``_classname__spam``, where ``classname`` is the 1742current class name with any leading underscores stripped. 1743 1744This doesn't guarantee privacy: an outside user can still deliberately access 1745the "_classname__spam" attribute, and private values are visible in the object's 1746``__dict__``. Many Python programmers never bother to use private variable 1747names at all. 1748 1749 1750My class defines __del__ but it is not called when I delete the object. 1751----------------------------------------------------------------------- 1752 1753There are several possible reasons for this. 1754 1755The :keyword:`del` statement does not necessarily call :meth:`~object.__del__` -- it simply 1756decrements the object's reference count, and if this reaches zero 1757:meth:`!__del__` is called. 1758 1759If your data structures contain circular links (e.g. a tree where each child has 1760a parent reference and each parent has a list of children) the reference counts 1761will never go back to zero. Once in a while Python runs an algorithm to detect 1762such cycles, but the garbage collector might run some time after the last 1763reference to your data structure vanishes, so your :meth:`!__del__` method may be 1764called at an inconvenient and random time. This is inconvenient if you're trying 1765to reproduce a problem. Worse, the order in which object's :meth:`!__del__` 1766methods are executed is arbitrary. You can run :func:`gc.collect` to force a 1767collection, but there *are* pathological cases where objects will never be 1768collected. 1769 1770Despite the cycle collector, it's still a good idea to define an explicit 1771``close()`` method on objects to be called whenever you're done with them. The 1772``close()`` method can then remove attributes that refer to subobjects. Don't 1773call :meth:`!__del__` directly -- :meth:`!__del__` should call ``close()`` and 1774``close()`` should make sure that it can be called more than once for the same 1775object. 1776 1777Another way to avoid cyclical references is to use the :mod:`weakref` module, 1778which allows you to point to objects without incrementing their reference count. 1779Tree data structures, for instance, should use weak references for their parent 1780and sibling references (if they need them!). 1781 1782.. XXX relevant for Python 3? 1783 1784 If the object has ever been a local variable in a function that caught an 1785 expression in an except clause, chances are that a reference to the object 1786 still exists in that function's stack frame as contained in the stack trace. 1787 Normally, calling :func:`sys.exc_clear` will take care of this by clearing 1788 the last recorded exception. 1789 1790Finally, if your :meth:`!__del__` method raises an exception, a warning message 1791is printed to :data:`sys.stderr`. 1792 1793 1794How do I get a list of all instances of a given class? 1795------------------------------------------------------ 1796 1797Python does not keep track of all instances of a class (or of a built-in type). 1798You can program the class's constructor to keep track of all instances by 1799keeping a list of weak references to each instance. 1800 1801 1802Why does the result of ``id()`` appear to be not unique? 1803-------------------------------------------------------- 1804 1805The :func:`id` builtin returns an integer that is guaranteed to be unique during 1806the lifetime of the object. Since in CPython, this is the object's memory 1807address, it happens frequently that after an object is deleted from memory, the 1808next freshly created object is allocated at the same position in memory. This 1809is illustrated by this example: 1810 1811>>> id(1000) # doctest: +SKIP 181213901272 1813>>> id(2000) # doctest: +SKIP 181413901272 1815 1816The two ids belong to different integer objects that are created before, and 1817deleted immediately after execution of the ``id()`` call. To be sure that 1818objects whose id you want to examine are still alive, create another reference 1819to the object: 1820 1821>>> a = 1000; b = 2000 1822>>> id(a) # doctest: +SKIP 182313901272 1824>>> id(b) # doctest: +SKIP 182513891296 1826 1827 1828When can I rely on identity tests with the *is* operator? 1829--------------------------------------------------------- 1830 1831The ``is`` operator tests for object identity. The test ``a is b`` is 1832equivalent to ``id(a) == id(b)``. 1833 1834The most important property of an identity test is that an object is always 1835identical to itself, ``a is a`` always returns ``True``. Identity tests are 1836usually faster than equality tests. And unlike equality tests, identity tests 1837are guaranteed to return a boolean ``True`` or ``False``. 1838 1839However, identity tests can *only* be substituted for equality tests when 1840object identity is assured. Generally, there are three circumstances where 1841identity is guaranteed: 1842 18431) Assignments create new names but do not change object identity. After the 1844assignment ``new = old``, it is guaranteed that ``new is old``. 1845 18462) Putting an object in a container that stores object references does not 1847change object identity. After the list assignment ``s[0] = x``, it is 1848guaranteed that ``s[0] is x``. 1849 18503) If an object is a singleton, it means that only one instance of that object 1851can exist. After the assignments ``a = None`` and ``b = None``, it is 1852guaranteed that ``a is b`` because ``None`` is a singleton. 1853 1854In most other circumstances, identity tests are inadvisable and equality tests 1855are preferred. In particular, identity tests should not be used to check 1856constants such as :class:`int` and :class:`str` which aren't guaranteed to be 1857singletons:: 1858 1859 >>> a = 1000 1860 >>> b = 500 1861 >>> c = b + 500 1862 >>> a is c 1863 False 1864 1865 >>> a = 'Python' 1866 >>> b = 'Py' 1867 >>> c = b + 'thon' 1868 >>> a is c 1869 False 1870 1871Likewise, new instances of mutable containers are never identical:: 1872 1873 >>> a = [] 1874 >>> b = [] 1875 >>> a is b 1876 False 1877 1878In the standard library code, you will see several common patterns for 1879correctly using identity tests: 1880 18811) As recommended by :pep:`8`, an identity test is the preferred way to check 1882for ``None``. This reads like plain English in code and avoids confusion with 1883other objects that may have boolean values that evaluate to false. 1884 18852) Detecting optional arguments can be tricky when ``None`` is a valid input 1886value. In those situations, you can create a singleton sentinel object 1887guaranteed to be distinct from other objects. For example, here is how 1888to implement a method that behaves like :meth:`dict.pop`:: 1889 1890 _sentinel = object() 1891 1892 def pop(self, key, default=_sentinel): 1893 if key in self: 1894 value = self[key] 1895 del self[key] 1896 return value 1897 if default is _sentinel: 1898 raise KeyError(key) 1899 return default 1900 19013) Container implementations sometimes need to augment equality tests with 1902identity tests. This prevents the code from being confused by objects such as 1903``float('NaN')`` that are not equal to themselves. 1904 1905For example, here is the implementation of 1906:meth:`collections.abc.Sequence.__contains__`:: 1907 1908 def __contains__(self, value): 1909 for v in self: 1910 if v is value or v == value: 1911 return True 1912 return False 1913 1914 1915How can a subclass control what data is stored in an immutable instance? 1916------------------------------------------------------------------------ 1917 1918When subclassing an immutable type, override the :meth:`~object.__new__` method 1919instead of the :meth:`~object.__init__` method. The latter only runs *after* an 1920instance is created, which is too late to alter data in an immutable 1921instance. 1922 1923All of these immutable classes have a different signature than their 1924parent class: 1925 1926.. testcode:: 1927 1928 from datetime import date 1929 1930 class FirstOfMonthDate(date): 1931 "Always choose the first day of the month" 1932 def __new__(cls, year, month, day): 1933 return super().__new__(cls, year, month, 1) 1934 1935 class NamedInt(int): 1936 "Allow text names for some numbers" 1937 xlat = {'zero': 0, 'one': 1, 'ten': 10} 1938 def __new__(cls, value): 1939 value = cls.xlat.get(value, value) 1940 return super().__new__(cls, value) 1941 1942 class TitleStr(str): 1943 "Convert str to name suitable for a URL path" 1944 def __new__(cls, s): 1945 s = s.lower().replace(' ', '-') 1946 s = ''.join([c for c in s if c.isalnum() or c == '-']) 1947 return super().__new__(cls, s) 1948 1949The classes can be used like this: 1950 1951.. doctest:: 1952 1953 >>> FirstOfMonthDate(2012, 2, 14) 1954 FirstOfMonthDate(2012, 2, 1) 1955 >>> NamedInt('ten') 1956 10 1957 >>> NamedInt(20) 1958 20 1959 >>> TitleStr('Blog: Why Python Rocks') 1960 'blog-why-python-rocks' 1961 1962 1963.. _faq-cache-method-calls: 1964 1965How do I cache method calls? 1966---------------------------- 1967 1968The two principal tools for caching methods are 1969:func:`functools.cached_property` and :func:`functools.lru_cache`. The 1970former stores results at the instance level and the latter at the class 1971level. 1972 1973The *cached_property* approach only works with methods that do not take 1974any arguments. It does not create a reference to the instance. The 1975cached method result will be kept only as long as the instance is alive. 1976 1977The advantage is that when an instance is no longer used, the cached 1978method result will be released right away. The disadvantage is that if 1979instances accumulate, so too will the accumulated method results. They 1980can grow without bound. 1981 1982The *lru_cache* approach works with methods that have :term:`hashable` 1983arguments. It creates a reference to the instance unless special 1984efforts are made to pass in weak references. 1985 1986The advantage of the least recently used algorithm is that the cache is 1987bounded by the specified *maxsize*. The disadvantage is that instances 1988are kept alive until they age out of the cache or until the cache is 1989cleared. 1990 1991This example shows the various techniques:: 1992 1993 class Weather: 1994 "Lookup weather information on a government website" 1995 1996 def __init__(self, station_id): 1997 self._station_id = station_id 1998 # The _station_id is private and immutable 1999 2000 def current_temperature(self): 2001 "Latest hourly observation" 2002 # Do not cache this because old results 2003 # can be out of date. 2004 2005 @cached_property 2006 def location(self): 2007 "Return the longitude/latitude coordinates of the station" 2008 # Result only depends on the station_id 2009 2010 @lru_cache(maxsize=20) 2011 def historic_rainfall(self, date, units='mm'): 2012 "Rainfall on a given date" 2013 # Depends on the station_id, date, and units. 2014 2015The above example assumes that the *station_id* never changes. If the 2016relevant instance attributes are mutable, the *cached_property* approach 2017can't be made to work because it cannot detect changes to the 2018attributes. 2019 2020To make the *lru_cache* approach work when the *station_id* is mutable, 2021the class needs to define the :meth:`~object.__eq__` and :meth:`~object.__hash__` 2022methods so that the cache can detect relevant attribute updates:: 2023 2024 class Weather: 2025 "Example with a mutable station identifier" 2026 2027 def __init__(self, station_id): 2028 self.station_id = station_id 2029 2030 def change_station(self, station_id): 2031 self.station_id = station_id 2032 2033 def __eq__(self, other): 2034 return self.station_id == other.station_id 2035 2036 def __hash__(self): 2037 return hash(self.station_id) 2038 2039 @lru_cache(maxsize=20) 2040 def historic_rainfall(self, date, units='cm'): 2041 'Rainfall on a given date' 2042 # Depends on the station_id, date, and units. 2043 2044 2045Modules 2046======= 2047 2048How do I create a .pyc file? 2049---------------------------- 2050 2051When a module is imported for the first time (or when the source file has 2052changed since the current compiled file was created) a ``.pyc`` file containing 2053the compiled code should be created in a ``__pycache__`` subdirectory of the 2054directory containing the ``.py`` file. The ``.pyc`` file will have a 2055filename that starts with the same name as the ``.py`` file, and ends with 2056``.pyc``, with a middle component that depends on the particular ``python`` 2057binary that created it. (See :pep:`3147` for details.) 2058 2059One reason that a ``.pyc`` file may not be created is a permissions problem 2060with the directory containing the source file, meaning that the ``__pycache__`` 2061subdirectory cannot be created. This can happen, for example, if you develop as 2062one user but run as another, such as if you are testing with a web server. 2063 2064Unless the :envvar:`PYTHONDONTWRITEBYTECODE` environment variable is set, 2065creation of a .pyc file is automatic if you're importing a module and Python 2066has the ability (permissions, free space, etc...) to create a ``__pycache__`` 2067subdirectory and write the compiled module to that subdirectory. 2068 2069Running Python on a top level script is not considered an import and no 2070``.pyc`` will be created. For example, if you have a top-level module 2071``foo.py`` that imports another module ``xyz.py``, when you run ``foo`` (by 2072typing ``python foo.py`` as a shell command), a ``.pyc`` will be created for 2073``xyz`` because ``xyz`` is imported, but no ``.pyc`` file will be created for 2074``foo`` since ``foo.py`` isn't being imported. 2075 2076If you need to create a ``.pyc`` file for ``foo`` -- that is, to create a 2077``.pyc`` file for a module that is not imported -- you can, using the 2078:mod:`py_compile` and :mod:`compileall` modules. 2079 2080The :mod:`py_compile` module can manually compile any module. One way is to use 2081the ``compile()`` function in that module interactively:: 2082 2083 >>> import py_compile 2084 >>> py_compile.compile('foo.py') # doctest: +SKIP 2085 2086This will write the ``.pyc`` to a ``__pycache__`` subdirectory in the same 2087location as ``foo.py`` (or you can override that with the optional parameter 2088``cfile``). 2089 2090You can also automatically compile all files in a directory or directories using 2091the :mod:`compileall` module. You can do it from the shell prompt by running 2092``compileall.py`` and providing the path of a directory containing Python files 2093to compile:: 2094 2095 python -m compileall . 2096 2097 2098How do I find the current module name? 2099-------------------------------------- 2100 2101A module can find out its own module name by looking at the predefined global 2102variable ``__name__``. If this has the value ``'__main__'``, the program is 2103running as a script. Many modules that are usually used by importing them also 2104provide a command-line interface or a self-test, and only execute this code 2105after checking ``__name__``:: 2106 2107 def main(): 2108 print('Running test...') 2109 ... 2110 2111 if __name__ == '__main__': 2112 main() 2113 2114 2115How can I have modules that mutually import each other? 2116------------------------------------------------------- 2117 2118Suppose you have the following modules: 2119 2120:file:`foo.py`:: 2121 2122 from bar import bar_var 2123 foo_var = 1 2124 2125:file:`bar.py`:: 2126 2127 from foo import foo_var 2128 bar_var = 2 2129 2130The problem is that the interpreter will perform the following steps: 2131 2132* main imports ``foo`` 2133* Empty globals for ``foo`` are created 2134* ``foo`` is compiled and starts executing 2135* ``foo`` imports ``bar`` 2136* Empty globals for ``bar`` are created 2137* ``bar`` is compiled and starts executing 2138* ``bar`` imports ``foo`` (which is a no-op since there already is a module named ``foo``) 2139* The import mechanism tries to read ``foo_var`` from ``foo`` globals, to set ``bar.foo_var = foo.foo_var`` 2140 2141The last step fails, because Python isn't done with interpreting ``foo`` yet and 2142the global symbol dictionary for ``foo`` is still empty. 2143 2144The same thing happens when you use ``import foo``, and then try to access 2145``foo.foo_var`` in global code. 2146 2147There are (at least) three possible workarounds for this problem. 2148 2149Guido van Rossum recommends avoiding all uses of ``from <module> import ...``, 2150and placing all code inside functions. Initializations of global variables and 2151class variables should use constants or built-in functions only. This means 2152everything from an imported module is referenced as ``<module>.<name>``. 2153 2154Jim Roskind suggests performing steps in the following order in each module: 2155 2156* exports (globals, functions, and classes that don't need imported base 2157 classes) 2158* ``import`` statements 2159* active code (including globals that are initialized from imported values). 2160 2161Van Rossum doesn't like this approach much because the imports appear in a 2162strange place, but it does work. 2163 2164Matthias Urlichs recommends restructuring your code so that the recursive import 2165is not necessary in the first place. 2166 2167These solutions are not mutually exclusive. 2168 2169 2170__import__('x.y.z') returns <module 'x'>; how do I get z? 2171--------------------------------------------------------- 2172 2173Consider using the convenience function :func:`~importlib.import_module` from 2174:mod:`importlib` instead:: 2175 2176 z = importlib.import_module('x.y.z') 2177 2178 2179When I edit an imported module and reimport it, the changes don't show up. Why does this happen? 2180------------------------------------------------------------------------------------------------- 2181 2182For reasons of efficiency as well as consistency, Python only reads the module 2183file on the first time a module is imported. If it didn't, in a program 2184consisting of many modules where each one imports the same basic module, the 2185basic module would be parsed and re-parsed many times. To force re-reading of a 2186changed module, do this:: 2187 2188 import importlib 2189 import modname 2190 importlib.reload(modname) 2191 2192Warning: this technique is not 100% fool-proof. In particular, modules 2193containing statements like :: 2194 2195 from modname import some_objects 2196 2197will continue to work with the old version of the imported objects. If the 2198module contains class definitions, existing class instances will *not* be 2199updated to use the new class definition. This can result in the following 2200paradoxical behaviour:: 2201 2202 >>> import importlib 2203 >>> import cls 2204 >>> c = cls.C() # Create an instance of C 2205 >>> importlib.reload(cls) 2206 <module 'cls' from 'cls.py'> 2207 >>> isinstance(c, cls.C) # isinstance is false?!? 2208 False 2209 2210The nature of the problem is made clear if you print out the "identity" of the 2211class objects:: 2212 2213 >>> hex(id(c.__class__)) 2214 '0x7352a0' 2215 >>> hex(id(cls.C)) 2216 '0x4198d0' 2217