Programming FAQ¶
Sommaire
- Programming FAQ
- General Questions
- Is there a source code level debugger with breakpoints, single-stepping, etc.?
- Is there a tool to help find bugs or perform static analysis?
- How can I create a stand-alone binary from a Python script?
- Are there coding standards or a style guide for Python programs?
- My program is too slow. How do I speed it up?
- Core Language
- Why am I getting an UnboundLocalError when the variable has a value?
- What are the rules for local and global variables in Python?
- Why do lambdas defined in a loop with different values all return the same result?
- How do I share global variables across modules?
- What are the « best practices » for using import in a module?
- Why are default values shared between objects?
- How can I pass optional or keyword parameters from one function to another?
- What is the difference between arguments and parameters?
- Why did changing list “y” also change list “x”?
- How do I write a function with output parameters (call by reference)?
- Comment construire une fonction d’ordre supérieur en Python ?
- Comment copier un objet en Python?
- Comment puis-je trouver les méthodes ou les attribues d’un objet?
- Comment mon code peut il découvrir le nom d’un objet?
- Qu’en est-il de la précédence de l’opérateur virgule ?
- Existe-t-il un équivalent à l’opérateur ternaire « ?: » du C ?
- Est-il possible d’écrire des programmes obscurcis (obfuscated) d’une ligne en Python ?
- Nombres et chaînes de caractères
- Comment puis-je écrire des entiers hexadécimaux ou octaux ?
- Pourquoi
-22 // 10
donne-t-il-3
? - Comment puis-je convertir une chaine de caractère en nombre?
- Comment convertir un nombre en chaine de caractère?
- Comment modifier une chaine de caractère « en place »?
- Comment utiliser des chaines de caractères pour appeler des fonctions/méthodes?
- Existe-t-il un équivalent à la fonction
chomp()
de Perl, pour retirer les caractères de fin de ligne d’une chaine de caractère ? - Existe-t-il un équivalent à
scanf()
ousscanf()
? - What does “UnicodeError: ASCII [decoding,encoding] error: ordinal not in range(128)” mean?
- Sequences (Tuples/Lists)
- Comment convertir les listes en tuples et inversement?
- Qu’est-ce qu’un indexe négatif?
- Comment itérer à rebours sur une séquence?
- Comment retirer les doublons d’une liste?
- Comment construire un tableau en Python?
- Comment puis-je créer une liste à plusieurs dimensions?
- Comment appliquer une méthode à une séquence d’objets?
- Why does a_tuple[i] += [“item”] raise an exception when the addition works?
- Dictionnaires
- Objets
- Qu’est-ce qu’une classe?
- Qu’est-ce qu’une méthode?
- Qu’est-ce que self?
- Comment puis-je vérifier si un objet est une instance d’une classe donnée ou d’une sous-classe de celui-ci?
- Qu’est-ce que la délégation?
- Comment appeler une méthode définie dans une classe de base depuis une classe dérivée qui la surcharge?
- Comment puis-je organiser mon code pour permettre de changer la classe de base plus facilement?
- Comment puis-je créer des données statiques de classe et des méthodes statiques de classe?
- Comment puis-je surcharger les constructeurs (ou méthodes) en Python?
- J’essaie d’utiliser
__spam
et j’obtiens une erreur à propos de_SomeClassName__spam
. - Ma classe définit
__del__
mais il n’est pas appelé lorsque je supprime l’objet. - How do I get a list of all instances of a given class?
- Why does the result of
id()
appear to be not unique?
- Modules
- General Questions
General Questions¶
Is there a source code level debugger with breakpoints, single-stepping, etc.?¶
Oui.
The pdb module is a simple but adequate console-mode debugger for Python. It is
part of the standard Python library, and is documented in the Library
Reference Manual
. You can also write your own debugger by using the code
for pdb as an example.
The IDLE interactive development environment, which is part of the standard Python distribution (normally available as Tools/scripts/idle), includes a graphical debugger.
PythonWin is a Python IDE that includes a GUI debugger based on pdb. The Pythonwin debugger colors breakpoints and has quite a few cool features such as debugging non-Pythonwin programs. Pythonwin is available as part of the Python for Windows Extensions project and as a part of the ActivePython distribution (see https://www.activestate.com/activepython).
Boa Constructor is an IDE and GUI builder that uses wxWidgets. It offers visual frame creation and manipulation, an object inspector, many views on the source like object browsers, inheritance hierarchies, doc string generated html documentation, an advanced debugger, integrated help, and Zope support.
Eric is an IDE built on PyQt and the Scintilla editing component.
Pydb is a version of the standard Python debugger pdb, modified for use with DDD (Data Display Debugger), a popular graphical debugger front end. Pydb can be found at http://bashdb.sourceforge.net/pydb/ and DDD can be found at https://www.gnu.org/software/ddd.
There are a number of commercial Python IDEs that include graphical debuggers. They include:
- Wing IDE (https://wingware.com/)
- Komodo IDE (https://komodoide.com/)
- PyCharm (https://www.jetbrains.com/pycharm/)
Is there a tool to help find bugs or perform static analysis?¶
Oui.
PyChecker is a static analysis tool that finds bugs in Python source code and warns about code complexity and style. You can get PyChecker from http://pychecker.sourceforge.net/.
Pylint is another tool that checks if a module satisfies a coding standard, and also makes it possible to write plug-ins to add a custom feature. In addition to the bug checking that PyChecker performs, Pylint offers some additional features such as checking line length, whether variable names are well-formed according to your coding standard, whether declared interfaces are fully implemented, and more. https://docs.pylint.org/ provides a full list of Pylint’s features.
How can I create a stand-alone binary from a Python script?¶
You don’t need the ability to compile Python to C code if all you want is a stand-alone program that users can download and run without having to install the Python distribution first. There are a number of tools that determine the set of modules required by a program and bind these modules together with a Python binary to produce a single executable.
One is to use the freeze tool, which is included in the Python source tree as
Tools/freeze
. It converts Python byte code to C arrays; a C compiler you can
embed all your modules into a new program, which is then linked with the
standard Python modules.
It works by scanning your source recursively for import statements (in both forms) and looking for the modules in the standard Python path as well as in the source directory (for built-in modules). It then turns the bytecode for modules written in Python into C code (array initializers that can be turned into code objects using the marshal module) and creates a custom-made config file that only contains those built-in modules which are actually used in the program. It then compiles the generated C code and links it with the rest of the Python interpreter to form a self-contained binary which acts exactly like your script.
Obviously, freeze requires a C compiler. There are several other utilities which don’t. One is Thomas Heller’s py2exe (Windows only) at
Another tool is Anthony Tuininga’s cx_Freeze.
Are there coding standards or a style guide for Python programs?¶
Yes. The coding style required for standard library modules is documented as PEP 8.
My program is too slow. How do I speed it up?¶
That’s a tough one, in general. There are many tricks to speed up Python code; consider rewriting parts in C as a last resort.
In some cases it’s possible to automatically translate Python to C or x86 assembly language, meaning that you don’t have to modify your code to gain increased speed.
Pyrex can compile a slightly modified version of Python code into a C extension, and can be used on many different platforms.
Psyco is a just-in-time compiler that translates Python code into x86 assembly language. If you can use it, Psyco can provide dramatic speedups for critical functions.
The rest of this answer will discuss various tricks for squeezing a bit more speed out of Python code. Never apply any optimization tricks unless you know you need them, after profiling has indicated that a particular function is the heavily executed hot spot in the code. Optimizations almost always make the code less clear, and you shouldn’t pay the costs of reduced clarity (increased development time, greater likelihood of bugs) unless the resulting performance benefit is worth it.
There is a page on the wiki devoted to performance tips.
Guido van Rossum has written up an anecdote related to optimization at https://www.python.org/doc/essays/list2str.
One thing to notice is that function and (especially) method calls are rather
expensive; if you have designed a purely OO interface with lots of tiny
functions that don’t do much more than get or set an instance variable or call
another method, you might consider using a more direct way such as directly
accessing instance variables. Also see the standard module profile
which
makes it possible to find out where your program is spending most of its time
(if you have some patience – the profiling itself can slow your program down by
an order of magnitude).
Remember that many standard optimization heuristics you may know from other programming experience may well apply to Python. For example it may be faster to send output to output devices using larger writes rather than smaller ones in order to reduce the overhead of kernel system calls. Thus CGI scripts that write all output in « one shot » may be faster than those that write lots of small pieces of output.
Also, be sure to use Python’s core features where appropriate. For example, slicing allows programs to chop up lists and other sequence objects in a single tick of the interpreter’s mainloop using highly optimized C implementations. Thus to get the same effect as:
L2 = []
for i in range(3):
L2.append(L1[i])
it is much shorter and far faster to use
L2 = list(L1[:3]) # "list" is redundant if L1 is a list.
Note that the functionally-oriented built-in functions such as map()
,
zip()
, and friends can be a convenient accelerator for loops that
perform a single task. For example to pair the elements of two lists
together:
>>> zip([1, 2, 3], [4, 5, 6])
[(1, 4), (2, 5), (3, 6)]
or to compute a number of sines:
>>> map(math.sin, (1, 2, 3, 4))
[0.841470984808, 0.909297426826, 0.14112000806, -0.756802495308]
The operation completes very quickly in such cases.
Other examples include the join()
and split()
methods
of string objects.
For example if s1..s7 are large (10K+) strings then
"".join([s1,s2,s3,s4,s5,s6,s7])
may be far faster than the more obvious
s1+s2+s3+s4+s5+s6+s7
, since the « summation » will compute many
subexpressions, whereas join()
does all the copying in one pass. For
manipulating strings, use the replace()
and the format()
methods
on string objects. Use regular expressions only when you’re
not dealing with constant string patterns. You may still use the old %
operations string % tuple
and string % dictionary
.
Be sure to use the list.sort()
built-in method to do sorting, and see the
sorting mini-HOWTO for examples
of moderately advanced usage. list.sort()
beats other techniques for
sorting in all but the most extreme circumstances.
Another common trick is to « push loops into functions or methods. » For example
suppose you have a program that runs slowly and you use the profiler to
determine that a Python function ff()
is being called lots of times. If you
notice that ff()
:
def ff(x):
... # do something with x computing result...
return result
tends to be called in loops like:
list = map(ff, oldlist)
ou :
for x in sequence:
value = ff(x)
... # do something with value...
then you can often eliminate function call overhead by rewriting ff()
to:
def ffseq(seq):
resultseq = []
for x in seq:
... # do something with x computing result...
resultseq.append(result)
return resultseq
and rewrite the two examples to list = ffseq(oldlist)
and to:
for value in ffseq(sequence):
... # do something with value...
Single calls to ff(x)
translate to ffseq([x])[0]
with little penalty.
Of course this technique is not always appropriate and there are other variants
which you can figure out.
You can gain some performance by explicitly storing the results of a function or method lookup into a local variable. A loop like:
for key in token:
dict[key] = dict.get(key, 0) + 1
resolves dict.get
every iteration. If the method isn’t going to change, a
slightly faster implementation is:
dict_get = dict.get # look up the method once
for key in token:
dict[key] = dict_get(key, 0) + 1
Default arguments can be used to determine values once, at compile time instead of at run time. This can only be done for functions or objects which will not be changed during program execution, such as replacing
def degree_sin(deg):
return math.sin(deg * math.pi / 180.0)
with
def degree_sin(deg, factor=math.pi/180.0, sin=math.sin):
return sin(deg * factor)
Because this trick uses default arguments for terms which should not be changed, it should only be used when you are not concerned with presenting a possibly confusing API to your users.
Core Language¶
Why am I getting an UnboundLocalError when the variable has a value?¶
It can be a surprise to get the UnboundLocalError in previously working code when it is modified by adding an assignment statement somewhere in the body of a function.
This code:
>>> x = 10
>>> def bar():
... print x
>>> bar()
10
works, but this code:
>>> x = 10
>>> def foo():
... print x
... x += 1
results in an UnboundLocalError:
>>> foo()
Traceback (most recent call last):
...
UnboundLocalError: local variable 'x' referenced before assignment
This is because when you make an assignment to a variable in a scope, that
variable becomes local to that scope and shadows any similarly named variable
in the outer scope. Since the last statement in foo assigns a new value to
x
, the compiler recognizes it as a local variable. Consequently when the
earlier print x
attempts to print the uninitialized local variable and
an error results.
In the example above you can access the outer scope variable by declaring it global:
>>> x = 10
>>> def foobar():
... global x
... print x
... x += 1
>>> foobar()
10
This explicit declaration is required in order to remind you that (unlike the superficially analogous situation with class and instance variables) you are actually modifying the value of the variable in the outer scope:
>>> print x
11
What are the rules for local and global variables in Python?¶
In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global.
Though a bit surprising at first, a moment’s consideration explains this. On
one hand, requiring global
for assigned variables provides a bar
against unintended side-effects. On the other hand, if global
was required
for all global references, you’d be using global
all the time. You’d have
to declare as global every reference to a built-in function or to a component of
an imported module. This clutter would defeat the usefulness of the global
declaration for identifying side-effects.
Why do lambdas defined in a loop with different values all return the same result?¶
Assume you use a for loop to define a few different lambdas (or even plain functions), e.g.:
>>> squares = []
>>> for x in range(5):
... squares.append(lambda: x**2)
This gives you a list that contains 5 lambdas that calculate x**2
. You
might expect that, when called, they would return, respectively, 0
, 1
,
4
, 9
, and 16
. However, when you actually try you will see that
they all return 16
:
>>> squares[2]()
16
>>> squares[4]()
16
This happens because x
is not local to the lambdas, but is defined in
the outer scope, and it is accessed when the lambda is called — not when it
is defined. At the end of the loop, the value of x
is 4
, so all the
functions now return 4**2
, i.e. 16
. You can also verify this by
changing the value of x
and see how the results of the lambdas change:
>>> x = 8
>>> squares[2]()
64
In order to avoid this, you need to save the values in variables local to the
lambdas, so that they don’t rely on the value of the global x
:
>>> squares = []
>>> for x in range(5):
... squares.append(lambda n=x: n**2)
Here, n=x
creates a new variable n
local to the lambda and computed
when the lambda is defined so that it has the same value that x
had at
that point in the loop. This means that the value of n
will be 0
in the first lambda, 1
in the second, 2
in the third, and so on.
Therefore each lambda will now return the correct result:
>>> squares[2]()
4
>>> squares[4]()
16
Note that this behaviour is not peculiar to lambdas, but applies to regular functions too.
What are the « best practices » for using import in a module?¶
In general, don’t use from modulename import *
. Doing so clutters the
importer’s namespace, and makes it much harder for linters to detect undefined
names.
Import modules at the top of a file. Doing so makes it clear what other modules your code requires and avoids questions of whether the module name is in scope. Using one import per line makes it easy to add and delete module imports, but using multiple imports per line uses less screen space.
It’s good practice if you import modules in the following order:
- standard library modules – e.g.
sys
,os
,getopt
,re
- third-party library modules (anything installed in Python’s site-packages directory) – e.g. mx.DateTime, ZODB, PIL.Image, etc.
- locally-developed modules
Only use explicit relative package imports. If you’re writing code that’s in
the package.sub.m1
module and want to import package.sub.m2
, do not just
write import m2
, even though it’s legal. Write from package.sub import
m2
or from . import m2
instead.
It is sometimes necessary to move imports to a function or class to avoid problems with circular imports. Gordon McMillan says:
Circular imports are fine where both modules use the « import <module> » form of import. They fail when the 2nd module wants to grab a name out of the first (« from module import name ») and the import is at the top level. That’s because names in the 1st are not yet available, because the first module is busy importing the 2nd.
In this case, if the second module is only used in one function, then the import can easily be moved into that function. By the time the import is called, the first module will have finished initializing, and the second module can do its import.
It may also be necessary to move imports out of the top level of code if some of the modules are platform-specific. In that case, it may not even be possible to import all of the modules at the top of the file. In this case, importing the correct modules in the corresponding platform-specific code is a good option.
Only move imports into a local scope, such as inside a function definition, if
it’s necessary to solve a problem such as avoiding a circular import or are
trying to reduce the initialization time of a module. This technique is
especially helpful if many of the imports are unnecessary depending on how the
program executes. You may also want to move imports into a function if the
modules are only ever used in that function. Note that loading a module the
first time may be expensive because of the one time initialization of the
module, but loading a module multiple times is virtually free, costing only a
couple of dictionary lookups. Even if the module name has gone out of scope,
the module is probably available in sys.modules
.
How can I pass optional or keyword parameters from one function to another?¶
Collect the arguments using the *
and **
specifiers in the function’s
parameter list; this gives you the positional arguments as a tuple and the
keyword arguments as a dictionary. You can then pass these arguments when
calling another function by using *
and **
:
def f(x, *args, **kwargs):
...
kwargs['width'] = '14.3c'
...
g(x, *args, **kwargs)
In the unlikely case that you care about Python versions older than 2.0, use
apply()
:
def f(x, *args, **kwargs):
...
kwargs['width'] = '14.3c'
...
apply(g, (x,)+args, kwargs)
What is the difference between arguments and parameters?¶
Parameters are defined by the names that appear in a function definition, whereas arguments are the values actually passed to a function when calling it. Parameters define what types of arguments a function can accept. For example, given the function definition:
def func(foo, bar=None, **kwargs):
pass
foo, bar and kwargs are parameters of func
. However, when calling
func
, for example:
func(42, bar=314, extra=somevar)
the values 42
, 314
, and somevar
are arguments.
Why did changing list “y” also change list “x”?¶
Si vous avez écrit du code comme :
>>> x = []
>>> y = x
>>> y.append(10)
>>> y
[10]
>>> x
[10]
you might be wondering why appending an element to y
changed x
too.
There are two factors that produce this result:
- Variables are simply names that refer to objects. Doing
y = x
doesn’t create a copy of the list – it creates a new variabley
that refers to the same objectx
refers to. This means that there is only one object (the list), and bothx
andy
refer to it. - Lists are mutable, which means that you can change their content.
After the call to append()
, the content of the mutable object has
changed from []
to [10]
. Since both the variables refer to the same
object, using either name accesses the modified value [10]
.
If we instead assign an immutable object to x
:
>>> x = 5 # ints are immutable
>>> y = x
>>> x = x + 1 # 5 can't be mutated, we are creating a new object here
>>> x
6
>>> y
5
we can see that in this case x
and y
are not equal anymore. This is
because integers are immutable, and when we do x = x + 1
we are not
mutating the int 5
by incrementing its value; instead, we are creating a
new object (the int 6
) and assigning it to x
(that is, changing which
object x
refers to). After this assignment we have two objects (the ints
6
and 5
) and two variables that refer to them (x
now refers to
6
but y
still refers to 5
).
Some operations (for example y.append(10)
and y.sort()
) mutate the
object, whereas superficially similar operations (for example y = y + [10]
and sorted(y)
) create a new object. In general in Python (and in all cases
in the standard library) a method that mutates an object will return None
to help avoid getting the two types of operations confused. So if you
mistakenly write y.sort()
thinking it will give you a sorted copy of y
,
you’ll instead end up with None
, which will likely cause your program to
generate an easily diagnosed error.
However, there is one class of operations where the same operation sometimes
has different behaviors with different types: the augmented assignment
operators. For example, +=
mutates lists but not tuples or ints (a_list
+= [1, 2, 3]
is equivalent to a_list.extend([1, 2, 3])
and mutates
a_list
, whereas some_tuple += (1, 2, 3)
and some_int += 1
create
new objects).
In other words:
- If we have a mutable object (
list
,dict
,set
, etc.), we can use some specific operations to mutate it and all the variables that refer to it will see the change. - If we have an immutable object (
str
,int
,tuple
, etc.), all the variables that refer to it will always see the same value, but operations that transform that value into a new value always return a new object.
If you want to know if two variables refer to the same object or not, you can
use the is
operator, or the built-in function id()
.
How do I write a function with output parameters (call by reference)?¶
Remember that arguments are passed by assignment in Python. Since assignment just creates references to objects, there’s no alias between an argument name in the caller and callee, and so no call-by-reference per se. You can achieve the desired effect in a number of ways.
By returning a tuple of the results:
def func2(a, b): a = 'new-value' # a and b are local names b = b + 1 # assigned to new objects return a, b # return new values x, y = 'old-value', 99 x, y = func2(x, y) print x, y # output: new-value 100
This is almost always the clearest solution.
En utilisant des variables globales. Ce qui n’est pas thread-safe, et n’est donc pas recommandé.
En passant un objet muable (modifiable sur place) :
def func1(a): a[0] = 'new-value' # 'a' references a mutable list a[1] = a[1] + 1 # changes a shared object args = ['old-value', 99] func1(args) print args[0], args[1] # output: new-value 100
En passant un dictionnaire, qui sera modifié :
def func3(args): args['a'] = 'new-value' # args is a mutable dictionary args['b'] = args['b'] + 1 # change it in-place args = {'a': 'old-value', 'b': 99} func3(args) print args['a'], args['b']
Ou regrouper les valeurs dans une instance de classe :
class callByRef: def __init__(self, **args): for (key, value) in args.items(): setattr(self, key, value) def func4(args): args.a = 'new-value' # args is a mutable callByRef args.b = args.b + 1 # change object in-place args = callByRef(a='old-value', b=99) func4(args) print args.a, args.b
Il n’y a pratiquement jamais de bonne raison de faire quelque chose d’aussi compliqué.
Votre meilleure option est de renvoyer un tuple contenant les multiples résultats.
Comment construire une fonction d’ordre supérieur en Python ?¶
Vous avez deux choix : vous pouvez utiliser les portées imbriquées ou vous pouvez utiliser des objets appelables. Par exemple, supposons que vous vouliez définir linear(a, b)
qui renvoie une fonction f(x)
qui calcule la valeur a*x+b
. En utilisant les portées imbriquées :
def linear(a, b):
def result(x):
return a * x + b
return result
Ou en utilisant un objet appelable :
class linear:
def __init__(self, a, b):
self.a, self.b = a, b
def __call__(self, x):
return self.a * x + self.b
dans les deux cas,
taxes = linear(0.3, 2)
donne un objet appelable où taxes(10e6) == 0.3 * 10e6 + 2
.
L’approche par objet appelable a le désavantage d’être légèrement plus lente et de produire un code légèrement plus long. Cependant, il faut noter qu’une collection d’objet appelables peuvent partager leur signatures par héritage :
class exponential(linear):
# __init__ inherited
def __call__(self, x):
return self.a * (x ** self.b)
Les objets peuvent encapsuler un état pour plusieurs méthodes :
class counter:
value = 0
def set(self, x):
self.value = x
def up(self):
self.value = self.value + 1
def down(self):
self.value = self.value - 1
count = counter()
inc, dec, reset = count.up, count.down, count.set
Ici inc()
, dec()
et reset()
agissent comme des fonctions partageant une même variable compteur.
Comment copier un objet en Python?¶
En général, essayez copy.copy()
ou copy.deepcopy()
pour le cas général. Tout les objets ne peuvent pas être copiés, mais la plupart le peuvent.
Certains objets peuvent être copiés plus facilement. Les Dictionnaires ont une méthode copy()
:
newdict = olddict.copy()
Les séquences peuvent être copiées via la syntaxe des tranches :
new_l = l[:]
Comment puis-je trouver les méthodes ou les attribues d’un objet?¶
Pour une instance x d’une classe définie par un utilisateur, dir(x)
renvoie une liste alphabétique des noms contenants les attributs de l’instance, et les attributs et méthodes définies par sa classe.
Comment mon code peut il découvrir le nom d’un objet?¶
De façon générale, il ne peut pas, par ce que les objets n’ont pas réellement de noms. Essentiellement, l’assignation attache un nom à une valeur; C’est vrai aussi pour les instructions def
et class
, à la différence que dans ce cas la valeur est appelable. Par exemple, dans le code suivant :
>>> class A:
... pass
...
>>> B = A
>>> a = B()
>>> b = a
>>> print b
<__main__.A instance at 0x16D07CC>
>>> print a
<__main__.A instance at 0x16D07CC>
Le fait que la classe ait un nom est discutable, bien qu’elles soit liée à deux noms, et qu’elle soit appelée via le nom B, l’instance crée déclare tout de même être une instance de la classe A. De même Il est impossible de dire si le nom de l’instance est a ou b, les deux noms sont attachés à la même valeur.
De façon général, il ne devrait pas être nécessaire pour votre application de « connaître le nom » d’une valeur particulière. À moins que vous soyez délibérément en train d’écrire un programme introspectif, c’est souvent une indication qu’un changement d’approche pourrait être bénéfique.
Sur comp.lang.python, Fredrik Lundh a donné un jour une excellente analogie pour répondre à cette question:
C’est pareil que trouver le nom du chat qui traîne devant votre porte : Le chat (objet) ne peux pas vous dire lui même son nom, et il s’en moque un peu – alors le meilleur moyen de savoir comment il s’appelle est de demander à tous vos voisins (espaces de noms) si c’est leur chat (objet)….
…et ne soyez pas surpris si vous découvrez qu’il est connus sous plusieurs noms différents, ou pas de nom du tout!
Qu’en est-il de la précédence de l’opérateur virgule ?¶
La virgule n’est pas un opérateur en Python. Observez la session suivante :
>>> "a" in "b", "a"
(False, 'a')
Comme la virgule n’est pas un opérateur, mais un séparateur entre deux expression, l’expression ci dessus, est évaluée de la même façon que si vous aviez écrit :
("a" in "b"), "a"
et non :
"a" in ("b", "a")
Ceci est vrai pour tous les opérateurs d’assignations (=
, +=
etc). Ce ne sont pas vraiment des opérateurs mais des délimiteurs syntaxiques dans les instructions d’assignation.
Existe-t-il un équivalent à l’opérateur ternaire « ?: » du C ?¶
Oui, cette fonctionnalité à été ajouté à partir de Python 2.5. La syntaxe est la suivante:
[on_true] if [expression] else [on_false]
x, y = 50, 25
small = x if x < y else y
Pour les versions précédentes de python la réponse serait « Non ».
Est-il possible d’écrire des programmes obscurcis (obfuscated) d’une ligne en Python ?¶
Oui. Cela est généralement réalisé en imbriquant les lambda
dans des lambda
. Observez les trois exemples suivants de Ulf Bartelt :
# Primes < 1000
print filter(None,map(lambda y:y*reduce(lambda x,y:x*y!=0,
map(lambda x,y=y:y%x,range(2,int(pow(y,0.5)+1))),1),range(2,1000)))
# First 10 Fibonacci numbers
print map(lambda x,f=lambda x,f:(f(x-1,f)+f(x-2,f)) if x>1 else 1: f(x,f),
range(10))
# Mandelbrot set
print (lambda Ru,Ro,Iu,Io,IM,Sx,Sy:reduce(lambda x,y:x+y,map(lambda y,
Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,Sy=Sy,L=lambda yc,Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,i=IM,
Sx=Sx,Sy=Sy:reduce(lambda x,y:x+y,map(lambda x,xc=Ru,yc=yc,Ru=Ru,Ro=Ro,
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
>=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(
64+F(Ru+x*(Ro-Ru)/Sx,yc,0,0,i)),range(Sx))):L(Iu+y*(Io-Iu)/Sy),range(Sy
))))(-2.1, 0.7, -1.2, 1.2, 30, 80, 24)
# \___ ___/ \___ ___/ | | |__ lines on screen
# V V | |______ columns on screen
# | | |__________ maximum of "iterations"
# | |_________________ range on y axis
# |____________________________ range on x axis
Les enfants, ne faîtes pas ça chez vous !
Nombres et chaînes de caractères¶
Comment puis-je écrire des entiers hexadécimaux ou octaux ?¶
Pour écrire un entier octal, faites précéder la valeur octale par un zéro, puis un « o » majuscule ou minuscule. Par exemple assigner la valeur octale « 10 » (8 en décimal) à la variable « a », tapez :
>>> a = 0o10
>>> a
8
L’hexadécimal est tout aussi simple, faîtes précéder le nombre hexadécimal par un zéro, puis un « x » majuscule ou minuscule. Les nombres hexadécimaux peuvent être écrit en majuscules ou en minuscules. Par exemple, dans l’interpréteur Python :
>>> a = 0xa5
>>> a
165
>>> b = 0XB2
>>> b
178
Pourquoi -22 // 10
donne-t-il -3
?¶
Cela est principalement due à la volonté que i % j
ait le même signe que j. Si vous voulez cela, vous voulez aussi :
i == (i // j) * j + (i % j)
Alors la division entière doit renvoyer l’entier inférieur. Le C demande aussi à ce que cette égalité soit vérifiée, et donc les compilateur qui tronquent i // j
ont besoin que i % j
ait le même signe que i
.
Il y a peu de cas d’utilisation réels pour i%j
quand j
est négatif. Quand j
est positif, il y en a beaucoup, et dans pratiquement tous, il est plus utile que i % j
soit >=0
. Si l’horloge dit 10h maintenant, que disait-elle il y a 200 heures? -190%12 == 2
est utile; -192 % 12 == -10
est un bug qui attends pour mordre.
Note
On Python 2, a / b
returns the same as a // b
if
__future__.division
is not in effect. This is also known as « classic »
division.
Comment puis-je convertir une chaine de caractère en nombre?¶
Pour les entiers, utilisez la fonction native int()
de type constructeur, par exemple int('144') == 144
. De façon similaire, float()
convertit en valeur flottante, par exemple float('144') == 144.0
.
Par défaut, ces fonctions interprètent les nombre en tant que décimaux, de telles façons que int('0144')==144
et int('0x144')
remontent ValueError
. int(string, base)
prends la base depuis laquelle il faut convertir dans le second argument, optionnel, donc int('0x144', 16) == 324
. Si la base donnée est 0, le nombre est interprété selon les règles Python: un “0” en tête indique octal, et “0x” indique un hexadécimal.
N’utilisez pas la fonction native eval()
si tout ce que vous avez besoin est de convertir des chaines en nombres. eval()
sera significativement plus lent et implique des risque de sécurité: quelqu’un pourrait vous envoyez une expression Python pouvant avoir des effets de bord indésirables. Par exemple, quelqu’un pourrait passer __import__('os').system("rm -rf $HOME")
ce qui aurait pour effet d’effacer votre répertoire personnel.
eval()
also has the effect of interpreting numbers as Python expressions,
so that e.g. eval('09')
gives a syntax error because Python regards numbers
starting with “0” as octal (base 8).
Comment convertir un nombre en chaine de caractère?¶
To convert, e.g., the number 144 to the string “144”, use the built-in type
constructor str()
. If you want a hexadecimal or octal representation, use
the built-in functions hex()
or oct()
. For fancy formatting, see
the Syntaxe de formatage de chaîne section, e.g. "{:04d}".format(144)
yields
'0144'
and "{:.3f}".format(1/3)
yields '0.333'
. You may also use
the % operator on strings. See the library reference
manual for details.
Comment modifier une chaine de caractère « en place »?¶
Vous ne pouvez pas, par ce que les chaines de caractères sont immuables, Si vous avez besoin d’un objet ayant une telle capacité, essayez de convertir la chaine en liste, ou utilisez le module array:
>>> import io
>>> s = "Hello, world"
>>> a = list(s)
>>> print a
['H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd']
>>> a[7:] = list("there!")
>>> ''.join(a)
'Hello, there!'
>>> import array
>>> a = array.array('c', s)
>>> print a
array('c', 'Hello, world')
>>> a[0] = 'y'; print a
array('c', 'yello, world')
>>> a.tostring()
'yello, world'
Comment utiliser des chaines de caractères pour appeler des fonctions/méthodes?¶
Il y a différentes techniques.
La meilleure est d’utiliser un dictionnaire qui fait correspondre les chaines de caractères à des fonctions. Le principal avantage de cette technique est que les chaines n’ont pas besoin d’être égales aux noms de fonctions. C’est aussi la principale façon d’imiter la construction « case » :
def a(): pass def b(): pass dispatch = {'go': a, 'stop': b} # Note lack of parens for funcs dispatch[get_input()]() # Note trailing parens to call function
Utiliser la fonction
getattr()
:import foo getattr(foo, 'bar')()
Notez que
getattr()
marche sur n’importe quel objet, ceci inclue les classes, les instances de classes, les modules et ainsi de suite.Ceci est utilisé dans plusieurs endroit de la bibliothèque standard, de cette façon :
class Foo: def do_foo(self): ... def do_bar(self): ... f = getattr(foo_instance, 'do_' + opname) f()
Utilisez
locals()
oueval()
pour résoudre le nom de fonction :def myFunc(): print "hello" fname = "myFunc" f = locals()[fname] f() f = eval(fname) f()
Note: En utilisant
eval()
est lent est dangereux. Si vous n’avez pas un contrôle absolu sur le contenu de la chaine de caractère, quelqu’un peut passer une chaine de caractère pouvant résulter en l’exécution de code arbitraire.
Existe-t-il un équivalent à la fonction chomp()
de Perl, pour retirer les caractères de fin de ligne d’une chaine de caractère ?¶
Starting with Python 2.2, you can use S.rstrip("\r\n")
to remove all
occurrences of any line terminator from the end of the string S
without
removing other trailing whitespace. If the string S
represents more than
one line, with several empty lines at the end, the line terminators for all the
blank lines will be removed:
>>> lines = ("line 1 \r\n"
... "\r\n"
... "\r\n")
>>> lines.rstrip("\n\r")
'line 1 '
Du fait que ce soit principalement utile en lisant un texte ligne à ligne, utiliser S.rstrip()
devrait marcher correctement.
Pour les versions plus anciennes de python, il y a deux substituts partiels disponibles.
- Si vous voulez retirer tous les espaces de fin de ligne, utilisez la méthode
rstrip()
des chaines de caractères. Cela retire tous les espaces de fin de ligne, pas seulement le caractère de fin de ligne. - Sinon, s’il y a seulement une ligne dans la chaine
S
, utilisezS.splitlines()[0]
.
Existe-t-il un équivalent à scanf()
ou sscanf()
?¶
Pas exactement.
Pour une simple analyse de chaine, l’approche la plus simple est généralement de découper la ligne en mots délimités par des espaces, en utilisant la méthode split()
des objets chaine de caractères, et ensuite de convertir les chaines de décimales en valeurs numériques en utilisant la fonction int()
ou float()
, split()
supporte un paramètre optionnel « sep » qui est utile si la ligne utilise autre chose que des espaces comme séparateur.
Pour les analyses plus compliquées, les expressions rationnelles sont plus puissantes que la fonction sscanf()
de C et mieux adaptées à la tâche.
What does “UnicodeError: ASCII [decoding,encoding] error: ordinal not in range(128)” mean?¶
This error indicates that your Python installation can handle only 7-bit ASCII strings. There are a couple ways to fix or work around the problem.
If your programs must handle data in arbitrary character set encodings, the
environment the application runs in will generally identify the encoding of the
data it is handing you. You need to convert the input to Unicode data using
that encoding. For example, a program that handles email or web input will
typically find character set encoding information in Content-Type headers. This
can then be used to properly convert input data to Unicode. Assuming the string
referred to by value
is encoded as UTF-8:
value = unicode(value, "utf-8")
will return a Unicode object. If the data is not correctly encoded as UTF-8,
the above call will raise a UnicodeError
exception.
If you only want strings converted to Unicode which have non-ASCII data, you can try converting them first assuming an ASCII encoding, and then generate Unicode objects if that fails:
try:
x = unicode(value, "ascii")
except UnicodeError:
value = unicode(value, "utf-8")
else:
# value was valid ASCII data
pass
It’s possible to set a default encoding in a file called sitecustomize.py
that’s part of the Python library. However, this isn’t recommended because
changing the Python-wide default encoding may cause third-party extension
modules to fail.
Note that on Windows, there is an encoding known as « mbcs », which uses an encoding specific to your current locale. In many cases, and particularly when working with COM, this may be an appropriate default encoding to use.
Sequences (Tuples/Lists)¶
Comment convertir les listes en tuples et inversement?¶
Le constructeur de type tuple(seq)
convertit toute séquence (en fait tout itérable) en un tuple avec les mêmes éléments dans le même ordre….
Par exemple tuple([1, 2, 3])
renvoi (1, 2, 3)
et tuple('abc')
renvoi ('a', 'b', 'c')
. Si l’argument est un tuple, cela ne crée pas une copie, mais renvoi le même objet, ce qui fait de tuple()
un fonction économique à appeler quand vous ne savez pas si votre objet est déjà un tuple.
Le constructeur de type list(seq)
convertit toute séquence ou itérable en liste contenant les mêmes éléments dans le même ordre. Par exemple, list((1,2,3))
renvoie [1,2,3]
et list('abc')
renvoie ['a','b','c']
. Si l’argument est une liste, il renvoie une copie, de la même façon que seq[:]
.
Qu’est-ce qu’un indexe négatif?¶
Les séquences Python sont indexées avec des nombres positifs aussi bien que négatifs. Pour les nombres positifs, 0 est le premier index, 1 est le second, et ainsi de suite. Pour les indexes négatifs, -1
est le dernier index, -2
est le pénultième (avant dernier), et ainsi de suite. On peut aussi dire que seq[-n]
est équivalent à seq[len(seq)-n]
.
Utiliser des indexes négatifs peut être très pratique. Par exemple S[:-1]
indique la chaine entière a l’exception du dernier caractère, ce qui est pratique pour retirer un caractère de fin de ligne en fin d’une chaine.
Comment itérer à rebours sur une séquence?¶
Utilisez la fonction embarquée reversed()
, qui est apparue en Python 2.4 :
for x in reversed(sequence):
... # do something with x ...
Cela ne modifiera pas votre séquence initiale, mais construira à la place une copie en ordre inverse pour itérer dessus.
Avec Python 2.3 vous pouvez utiliser la syntaxe étendue de tranches :
for x in sequence[::-1]:
... # do something with x ...
Comment retirer les doublons d’une liste?¶
Lisez le Python Cookbook pour trouver une longue discussion sur les nombreuses façons de faire cela:
Si changer l’ordre de la liste ne vous dérange pas, commencez par trier celle ci, puis parcourez la d’un bout à l’autre, en supprimant les doublons trouvés en chemin :
if mylist:
mylist.sort()
last = mylist[-1]
for i in range(len(mylist)-2, -1, -1):
if last == mylist[i]:
del mylist[i]
else:
last = mylist[i]
Si tous les éléments de la liste peuvent être utilisés comme des clés de dictionnaire (cad, elles sont toutes hashables) ceci est souvent plus rapide:
d = {}
for x in mylist:
d[x] = 1
mylist = list(d.keys())
En Python 2.5 et suivant, la forme suivante est possible à la place:
mylist = list(set(mylist))
Ceci convertis la liste en un ensemble, ce qui supprime automatiquement les doublons, puis la transforme à nouveau en liste.
Comment construire un tableau en Python?¶
Utilisez une liste :
["this", 1, "is", "an", "array"]
Les listes ont un cout équivalent à celui des tableau C ou Pascal; la principale différence est qu’une liste Python peut contenir des objets de différents types.
Le module array
fournit des méthodes pour créer des tableaux de types fixes dans une représentation compacte, mais ils sont plus lents à indexer que les listes. Notez aussi que l’extension Numeric
et d’autres, fournissent différentes structures de types tableaux, avec des caractéristiques différentes.
Pour obtenir des listes chainées de type Lisp, vous pouvez émuler les cons cells en utilisant des tuples :
lisp_list = ("like", ("this", ("example", None) ) )
Si vous voulez pouvoir modifier les éléments, utilisez une liste plutôt qu’un tuple. Ici la version équivalente au car de Lisp est lisp_list[0]
et l’équivalent à cdr est list_lip[1]
. Ne faites ceci que si vous êtes réellement sûr d’en avoir besoin, cette méthode est en générale bien plus lente que les listes Python.
Comment puis-je créer une liste à plusieurs dimensions?¶
Vous avez probablement essayé de créer une liste à plusieurs dimensions de cette façon :
>>> A = [[None] * 2] * 3
Cela semble correct quand vous essayer de l’afficher:
>>> A
[[None, None], [None, None], [None, None]]
Mais quand vous assignez une valeur, elle apparait en de multiples endroits:
>>> A[0][0] = 5
>>> A
[[5, None], [5, None], [5, None]]
La raison en est que dupliquer une liste en utilisant *
ne crée pas de copies, cela crée seulement des références aux objets existants. Le *3
crée une liste contenant trois références à la même liste de longueur deux. Un changement dans une colonne apparaîtra donc dans toutes les colonnes. Ce qui n’est de façon quasi certaine, pas ce que vous souhaitez.
L’approche suggérée est de créer une liste de la longueur désiré d’abords, puis de remplir tous les éléments avec une chaîne nouvellement créée :
A = [None] * 3
for i in range(3):
A[i] = [None] * 2
Cette liste générée contient trois listes différentes de longueur deux. Vous pouvez aussi utilisez la notation de compréhension de listes :
w, h = 2, 3
A = [[None] * w for i in range(h)]
Or, you can use an extension that provides a matrix datatype; NumPy is the best known.
Comment appliquer une méthode à une séquence d’objets?¶
Utilisez une compréhension de liste :
result = [obj.method() for obj in mylist]
More generically, you can try the following function:
def method_map(objects, method, arguments):
"""method_map([a,b], "meth", (1,2)) gives [a.meth(1,2), b.meth(1,2)]"""
nobjects = len(objects)
methods = map(getattr, objects, [method]*nobjects)
return map(apply, methods, [arguments]*nobjects)
Why does a_tuple[i] += [“item”] raise an exception when the addition works?¶
This is because of a combination of the fact that augmented assignment operators are assignment operators, and the difference between mutable and immutable objects in Python.
This discussion applies in general when augmented assignment operators are
applied to elements of a tuple that point to mutable objects, but we’ll use
a list
and +=
as our exemplar.
Si vous écrivez :
>>> a_tuple = (1, 2)
>>> a_tuple[0] += 1
Traceback (most recent call last):
...
TypeError: 'tuple' object does not support item assignment
The reason for the exception should be immediately clear: 1
is added to the
object a_tuple[0]
points to (1
), producing the result object, 2
,
but when we attempt to assign the result of the computation, 2
, to element
0
of the tuple, we get an error because we can’t change what an element of
a tuple points to.
Under the covers, what this augmented assignment statement is doing is approximately this:
>>> result = a_tuple[0] + 1
>>> a_tuple[0] = result
Traceback (most recent call last):
...
TypeError: 'tuple' object does not support item assignment
It is the assignment part of the operation that produces the error, since a tuple is immutable.
When you write something like:
>>> a_tuple = (['foo'], 'bar')
>>> a_tuple[0] += ['item']
Traceback (most recent call last):
...
TypeError: 'tuple' object does not support item assignment
The exception is a bit more surprising, and even more surprising is the fact that even though there was an error, the append worked:
>>> a_tuple[0]
['foo', 'item']
To see why this happens, you need to know that (a) if an object implements an
__iadd__
magic method, it gets called when the +=
augmented assignment
is executed, and its return value is what gets used in the assignment statement;
and (b) for lists, __iadd__
is equivalent to calling extend
on the list
and returning the list. That’s why we say that for lists, +=
is a
« shorthand » for list.extend
:
>>> a_list = []
>>> a_list += [1]
>>> a_list
[1]
C’est équivalent à :
>>> result = a_list.__iadd__([1])
>>> a_list = result
The object pointed to by a_list has been mutated, and the pointer to the
mutated object is assigned back to a_list
. The end result of the
assignment is a no-op, since it is a pointer to the same object that a_list
was previously pointing to, but the assignment still happens.
Thus, in our tuple example what is happening is equivalent to:
>>> result = a_tuple[0].__iadd__(['item'])
>>> a_tuple[0] = result
Traceback (most recent call last):
...
TypeError: 'tuple' object does not support item assignment
The __iadd__
succeeds, and thus the list is extended, but even though
result
points to the same object that a_tuple[0]
already points to,
that final assignment still results in an error, because tuples are immutable.
Dictionnaires¶
Comment puis-je faire afficher les éléments d’un dictionnaire dans un ordre consistant?¶
Vous ne pouvez pas. Les dictionnaires enregistrent leurs clées dans un ordre non prévisible, l’ordre d’affichage des éléments d’un dictionnaire sera donc de la même façon imprévisible.
Cela peut être frustrant si vous voulez sauvegarder une version affichable dans un fichier, faire des changement puis comparer avec un autre dictionnaire affiché. Dans ce cas, utilisez le module pprint`
pour afficher joliement le dictionnaire; les éléments seront présentés triés par clés.
Une solution plus compliquée est de sousclasser dict
pour créer une classe``SorterDict`` qui s’affiche de façon prévisible. Voici une implémentation simple d’une telle classe:
class SortedDict(dict):
def __repr__(self):
keys = sorted(self.keys())
result = ("{!r}: {!r}".format(k, self[k]) for k in keys)
return "{{{}}}".format(", ".join(result))
__str__ = __repr__
Cela marchera dans la plupart des situations que vous pourriez rencontrer, même si c’est loin d’être une solution parfaite. Le plus gros problème avec cette solution est que si certaines valeurs dans le dictionnaire sont aussi des dictionnaire, alors elles ne seront pas présentées dans un ordre particulier.
Je souhaite faire un tri compliqué: peut on faire une transformation de Schwartz en Python?¶
The technique, attributed to Randal Schwartz of the Perl community, sorts the
elements of a list by a metric which maps each element to its « sort value ». In
Python, use the key
argument for the sort()
function:
Isorted = L[:]
Isorted.sort(key=lambda s: int(s[10:15]))
Comment puis-je trier une liste en fonction des valeurs d’une autre liste?¶
Merge them into a single list of tuples, sort the resulting list, and then pick out the element you want.
>>> list1 = ["what", "I'm", "sorting", "by"]
>>> list2 = ["something", "else", "to", "sort"]
>>> pairs = zip(list1, list2)
>>> pairs
[('what', 'something'), ("I'm", 'else'), ('sorting', 'to'), ('by', 'sort')]
>>> pairs.sort()
>>> result = [ x[1] for x in pairs ]
>>> result
['else', 'sort', 'to', 'something']
Une alternative pour la dernière étape est :
>>> result = []
>>> for p in pairs: result.append(p[1])
Si vous trouvez cela plus lisible, vous préférez peut-être utiliser ceci à la place de la compréhension de la liste finale. Toutefois, ceci est presque deux fois plus lent pour les longues listes. Pourquoi? Tout d’abord, append ()
doit réaffecter la mémoire, et si il utilise quelques astuces pour éviter de le faire à chaque fois, il doit encore le faire de temps en temps, ce qui coûte assez cher. Deuxièmement, l’expression result.append
exige une recherche d’attribut supplémentaire, et enfin, tous ces appels de fonction impactent la vitesse d’exécution.
Objets¶
Qu’est-ce qu’une classe?¶
Une classe est le type d’objet particulier créé par l’exécution d’une déclaration de classe. Les objets de classe sont utilisés comme modèles pour créer des objets, qui incarnent à la fois les données (attributs) et le code (méthodes) spécifiques à un type de données.
Une classe peut être fondée sur une ou plusieurs autres classes, appelée sa ou ses classes de base. Il hérite alors les attributs et les méthodes de ses classes de base. Cela permet à un modèle d’objet d’être successivement raffinés par héritage. Vous pourriez avoir une classe générique Mailbox
qui fournit des méthodes d’accès de base pour une boîte aux lettres, et sous-classes telles que MboxMailbox
, MaildirMailbox
, OutlookMailbox
qui gèrent les différents formats de boîtes aux lettres spécifiques.
Qu’est-ce qu’une méthode?¶
Une méthode est une fonction sur un objet x
appelez normalement comme x.name(arguments…)
. Les méthodes sont définies comme des fonctions à l’intérieur de la définition de classe :
class C:
def meth(self, arg):
return arg * 2 + self.attribute
Qu’est-ce que self?¶
Self est simplement un nom conventionnel pour le premier argument d’une méthode. Une méthode définie comme meth(self, a, b, c)
doit être appelée en tant que x.meth(a, b, c)
, pour une instance x
de la classe dans laquelle elle est définie, la méthode appelée considérera qu’elle est appelée meth(x, a, b, c)
.
Voir aussi Pourquoi « self » doit-il être explicitement utilisé dans les définitions et les appels de méthode ?.
Comment puis-je vérifier si un objet est une instance d’une classe donnée ou d’une sous-classe de celui-ci?¶
Use the built-in function isinstance(obj, cls)
. You can check if an object
is an instance of any of a number of classes by providing a tuple instead of a
single class, e.g. isinstance(obj, (class1, class2, ...))
, and can also
check whether an object is one of Python’s built-in types, e.g.
isinstance(obj, str)
or isinstance(obj, (int, long, float, complex))
.
Notez que la plupart des programmes n’utilisent pas isInstance()
sur les classes définies par l’utilisateur, très souvent. Si vous développez vous-même les classes, un style plus appropriée orientée objet est de définir des méthodes sur les classes qui encapsulent un comportement particulier, au lieu de vérifier la classe de l’objet et de faire quelque chose de différent en fonction de sa classe. Par exemple, si vous avez une fonction qui fait quelque chose :
def search(obj):
if isinstance(obj, Mailbox):
... # code to search a mailbox
elif isinstance(obj, Document):
... # code to search a document
elif ...
Une meilleure approche est de définir une méthode search()
sur toutes les classes et qu’il suffit d’appeler :
class Mailbox:
def search(self):
... # code to search a mailbox
class Document:
def search(self):
... # code to search a document
obj.search()
Qu’est-ce que la délégation?¶
La délégation est une technique orientée objet (aussi appelé un modèle de conception). Disons que vous avez un objet x
et que vous souhaitez modifier le comportement d’une seule de ses méthodes. Vous pouvez créer une nouvelle classe qui fournit une nouvelle implémentation de la méthode qui vous intéresse dans l’évolution et les délégués de toutes les autres méthodes la méthode correspondante de x
.
Les programmeurs Python peuvent facilement mettre en œuvre la délégation. Par exemple, la classe suivante implémente une classe qui se comporte comme un fichier, mais convertit toutes les données écrites en majuscules :
class UpperOut:
def __init__(self, outfile):
self._outfile = outfile
def write(self, s):
self._outfile.write(s.upper())
def __getattr__(self, name):
return getattr(self._outfile, name)
Ici, la classe UpperOut
redéfinit la méthode write()
pour convertir la chaîne d’argument en majuscules avant d’appeler la méthode sous-jacentes self.__outfile.write()
. Toutes les autres méthodes sont déléguées à l’objet sous-jacent self.__outfile
. La délégation se fait par la méthode __getattr__
, consulter the language reference pour plus d’informations sur le contrôle d’accès d’attribut.
Notez que pour une utilisation plus générale de la délégation, les choses peuvent se compliquer. Lorsque les attributs doivent être définis aussi bien que récupérés, la classe doit définir une méthode __setattr__()
aussi, et il doit le faire avec soin. La mise en œuvre basique de la méthode __setattr__()
est à peu près équivalent à ce qui suit :
class X:
...
def __setattr__(self, name, value):
self.__dict__[name] = value
...
La plupart des implémentations de __setattr__()
doivent modifier self.__dict__
pour stocker l’état locale de self sans provoquer une récursion infinie.
Comment appeler une méthode définie dans une classe de base depuis une classe dérivée qui la surcharge?¶
Si vous utilisez des new-style classes, Utilisez la fonction native super()
:
class Derived(Base):
def meth(self):
super(Derived, self).meth()
If you’re using classic classes: For a class definition such as class
Derived(Base): ...
you can call method meth()
defined in Base
(or one
of Base
’s base classes) as Base.meth(self, arguments...)
. Here,
Base.meth
is an unbound method, so you need to provide the self
argument.
Comment puis-je organiser mon code pour permettre de changer la classe de base plus facilement?¶
Vous pouvez définir un alias pour la classe de base, lui attribuer la classe de base réelle avant la définition de classe, et utiliser l’alias au long de votre classe. Ensuite, tout ce que vous devez changer est la valeur attribuée à l’alias. Incidemment, cette astuce est également utile si vous voulez décider dynamiquement (par exemple en fonction de la disponibilité des ressources) la classe de base à utiliser. Exemple :
BaseAlias = <real base class>
class Derived(BaseAlias):
def meth(self):
BaseAlias.meth(self)
...
Comment puis-je créer des données statiques de classe et des méthodes statiques de classe?¶
Tant les données statiques que les méthodes statiques (dans le sens de C + + ou Java) sont pris en charge en Python.
Pour les données statiques, il suffit de définir un attribut de classe. Pour attribuer une nouvelle valeur à l’attribut, vous devez explicitement utiliser le nom de classe dans l’affectation :
class C:
count = 0 # number of times C.__init__ called
def __init__(self):
C.count = C.count + 1
def getcount(self):
return C.count # or return self.count
c.count
se réfère également à C.count
pour tout c
telle que isInstance (c, C)
est vrai, sauf remplacement par c
lui-même ou par une classe sur le chemin de recherche de classe de base de c.__class__
jusqu’à C
.
Attention: dans une méthode de C, une affectation comme self.count = 42
crée une nouvelle instance et sans rapport avec le nom count
dans dans le dictionnaire de données de self
. La redéfinition d’une donnée statique de classe doit toujours spécifier la classe que l’on soit à l’intérieur d’une méthode ou non :
C.count = 314
Les méthodes statiques sont possibles depuis Python 2.2:
class C:
def static(arg1, arg2, arg3):
# No 'self' parameter!
...
static = staticmethod(static)
Avec les décorateurs de Python 2.4, cela peut aussi s’écrire:
class C:
@staticmethod
def static(arg1, arg2, arg3):
# No 'self' parameter!
...
Cependant, d’une manière beaucoup plus simple pour obtenir l’effet d’une méthode statique se fait par une simple fonction au niveau du module :
def getcount():
return C.count
Si votre code est structuré de manière à définir une classe (ou bien la hiérarchie des classes connexes) par module, ceci fournira l’encapsulation souhaitée.
Comment puis-je surcharger les constructeurs (ou méthodes) en Python?¶
Cette réponse s’applique en fait à toutes les méthodes, mais la question vient généralement en premier dans le contexte des constructeurs.
In C++ you’d write
class C {
C() { cout << "No arguments\n"; }
C(int i) { cout << "Argument is " << i << "\n"; }
}
En Python, vous devez écrire un constructeur unique qui considère tous les cas en utilisant des arguments par défaut. Par exemple :
class C:
def __init__(self, i=None):
if i is None:
print "No arguments"
else:
print "Argument is", i
Ce n’est pas tout à fait équivalent, mais suffisamment proche dans la pratique.
Vous pouvez aussi utiliser une liste d’arguments de longueur variable, par exemple :
def __init__(self, *args):
...
La même approche fonctionne pour toutes les définitions de méthode.
J’essaie d’utiliser __spam
et j’obtiens une erreur à propos de _SomeClassName__spam
.¶
Les noms de variables commençant avec deux tirets bas sont «déformés», c’est un moyen simple mais efficace de définir variables privées à une classe. Tout identifiant de la forme __spam
(commençant par au moins deux tirets bas et se terminant par au plus un tiret bas) est textuellement remplacé par _classname__spam
, où classname
est le nom de la classe en cours dont les éventuels tirets bas ont été retirés.
Cela ne garantit pas la privauté de l’accès : un utilisateur extérieur peut encore délibérément accéder à l’attribut _classname__spam
, et les valeurs privées sont visibles dans l’objet __dict__
. De nombreux programmeurs Python ne prennent jamais la peine d’utiliser des noms de variable privée.
Ma classe définit __del__
mais il n’est pas appelé lorsque je supprime l’objet.¶
Il y a plusieurs raisons possibles pour cela.
La commande del n’appelle pas forcément __del__()
— il décrémente simplement le compteur de références de l’objet, et si celui ci arrive à zéro __del__()
est appelée.
If your data structures contain circular links (e.g. a tree where each child has
a parent reference and each parent has a list of children) the reference counts
will never go back to zero. Once in a while Python runs an algorithm to detect
such cycles, but the garbage collector might run some time after the last
reference to your data structure vanishes, so your __del__()
method may be
called at an inconvenient and random time. This is inconvenient if you’re trying
to reproduce a problem. Worse, the order in which object’s __del__()
methods are executed is arbitrary. You can run gc.collect()
to force a
collection, but there are pathological cases where objects will never be
collected.
Despite the cycle collector, it’s still a good idea to define an explicit
close()
method on objects to be called whenever you’re done with them. The
close()
method can then remove attributes that refer to subobjecs. Don’t
call __del__()
directly – __del__()
should call close()
and
close()
should make sure that it can be called more than once for the same
object.
Another way to avoid cyclical references is to use the weakref
module,
which allows you to point to objects without incrementing their reference count.
Tree data structures, for instance, should use weak references for their parent
and sibling references (if they need them!).
If the object has ever been a local variable in a function that caught an
expression in an except clause, chances are that a reference to the object still
exists in that function’s stack frame as contained in the stack trace.
Normally, calling sys.exc_clear()
will take care of this by clearing the
last recorded exception.
Finally, if your __del__()
method raises an exception, a warning message
is printed to sys.stderr
.
How do I get a list of all instances of a given class?¶
Python does not keep track of all instances of a class (or of a built-in type). You can program the class’s constructor to keep track of all instances by keeping a list of weak references to each instance.
Why does the result of id()
appear to be not unique?¶
The id()
builtin returns an integer that is guaranteed to be unique during
the lifetime of the object. Since in CPython, this is the object’s memory
address, it happens frequently that after an object is deleted from memory, the
next freshly created object is allocated at the same position in memory. This
is illustrated by this example:
>>> id(1000)
13901272
>>> id(2000)
13901272
The two ids belong to different integer objects that are created before, and
deleted immediately after execution of the id()
call. To be sure that
objects whose id you want to examine are still alive, create another reference
to the object:
>>> a = 1000; b = 2000
>>> id(a)
13901272
>>> id(b)
13891296
Modules¶
How do I create a .pyc file?¶
When a module is imported for the first time (or when the source is more recent
than the current compiled file) a .pyc
file containing the compiled code
should be created in the same directory as the .py
file.
One reason that a .pyc
file may not be created is permissions problems with
the directory. This can happen, for example, if you develop as one user but run
as another, such as if you are testing with a web server. Creation of a .pyc
file is automatic if you’re importing a module and Python has the ability
(permissions, free space, etc…) to write the compiled module back to the
directory.
Running Python on a top level script is not considered an import and no
.pyc
will be created. For example, if you have a top-level module
foo.py
that imports another module xyz.py
, when you run foo
,
xyz.pyc
will be created since xyz
is imported, but no foo.pyc
file
will be created since foo.py
isn’t being imported.
If you need to create foo.pyc
– that is, to create a .pyc
file for a module
that is not imported – you can, using the py_compile
and
compileall
modules.
The py_compile
module can manually compile any module. One way is to use
the compile()
function in that module interactively:
>>> import py_compile
>>> py_compile.compile('foo.py')
This will write the .pyc
to the same location as foo.py
(or you can
override that with the optional parameter cfile
).
You can also automatically compile all files in a directory or directories using
the compileall
module. You can do it from the shell prompt by running
compileall.py
and providing the path of a directory containing Python files
to compile:
python -m compileall .
How do I find the current module name?¶
A module can find out its own module name by looking at the predefined global
variable __name__
. If this has the value '__main__'
, the program is
running as a script. Many modules that are usually used by importing them also
provide a command-line interface or a self-test, and only execute this code
after checking __name__
:
def main():
print 'Running test...'
...
if __name__ == '__main__':
main()
How can I have modules that mutually import each other?¶
Suppose you have the following modules:
foo.py:
from bar import bar_var
foo_var = 1
bar.py:
from foo import foo_var
bar_var = 2
The problem is that the interpreter will perform the following steps:
- main imports foo
- Empty globals for foo are created
- foo is compiled and starts executing
- foo imports bar
- Empty globals for bar are created
- bar is compiled and starts executing
- bar imports foo (which is a no-op since there already is a module named foo)
- bar.foo_var = foo.foo_var
The last step fails, because Python isn’t done with interpreting foo
yet and
the global symbol dictionary for foo
is still empty.
The same thing happens when you use import foo
, and then try to access
foo.foo_var
in global code.
There are (at least) three possible workarounds for this problem.
Guido van Rossum recommends avoiding all uses of from <module> import ...
,
and placing all code inside functions. Initializations of global variables and
class variables should use constants or built-in functions only. This means
everything from an imported module is referenced as <module>.<name>
.
Jim Roskind suggests performing steps in the following order in each module:
- exports (globals, functions, and classes that don’t need imported base classes)
import
statements- active code (including globals that are initialized from imported values).
van Rossum doesn’t like this approach much because the imports appear in a strange place, but it does work.
Matthias Urlichs recommends restructuring your code so that the recursive import is not necessary in the first place.
These solutions are not mutually exclusive.
__import__(“x.y.z”) returns <module “x”>; how do I get z?¶
Consider using the convenience function import_module()
from
importlib
instead:
z = importlib.import_module('x.y.z')
When I edit an imported module and reimport it, the changes don’t show up. Why does this happen?¶
For reasons of efficiency as well as consistency, Python only reads the module file on the first time a module is imported. If it didn’t, in a program consisting of many modules where each one imports the same basic module, the basic module would be parsed and re-parsed many times. To force rereading of a changed module, do this:
import modname
reload(modname)
Warning: this technique is not 100% fool-proof. In particular, modules containing statements like
from modname import some_objects
will continue to work with the old version of the imported objects. If the module contains class definitions, existing class instances will not be updated to use the new class definition. This can result in the following paradoxical behaviour:
>>> import cls
>>> c = cls.C() # Create an instance of C
>>> reload(cls)
<module 'cls' from 'cls.pyc'>
>>> isinstance(c, cls.C) # isinstance is false?!?
False
The nature of the problem is made clear if you print out the class objects:
>>> c.__class__
<class cls.C at 0x7352a0>
>>> cls.C
<class cls.C at 0x4198d0>