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