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