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