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