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