Mieux programmer en Python 🇫🇷

Xiaoou WANG

Les grands principes

[1]:
import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

N’utilisez pas des syntaxes exotiques

[1]:
#! don't
a = [1, 2, 3, 4]
c = 'abcdef'
print(a[::-1])
print(c[::-1])
#* do
print(list(reversed(a)))
print(list(reversed(c)))
[4, 3, 2, 1]
fedcba

Évitez les keywords de Python pour des noms de variables.

[5]:
#! don't
def funA(list, num):
    for element in list:
        if num == element:
            return True
        else:
            pass

#* do
def find_num(searchList, num):
    for listValue in searchList:
        if num == listValue:
            return True
        else:
            pass

Implémenter Switch en Python

[3]:
#* implement switch case in python
def f(x):
    return {
      0: "0",
      1: "1",
      2: "2"
    }.get(x, "???")

print(f(1)) # 1
print(f(4)) # ???
1
???

Espaces et lignes

[ ]:
#* Use space
#! don't
import random
guess_made = 0
number = guess_made

#* Do
import random

guess_made = 0

number = guess_made

#! don't
if number==3:
    print(4)

#* do
if number == 3:
    print(4)

Expression ternaire

[5]:
# Ternary expression in Python
print(4) if True else print(4)

4

Refactoring

Pour un grand projet, la bonne organisation des codes est primordiale et différencie les débutants des chevronnés.

Une bonne pratique serait de stocker les constantes dans un même fichier et d’en importer là où il en faut.

[14]:
#* Put all constants in one file `constant.py` in this example
import constant
print(constant.MY_CONSTANT)
50

Sucres syntaxiques

[27]:
%%time
#! don't
x = 3
y = 4

temp = x
x = y
y = temp
CPU times: user 2 µs, sys: 0 ns, total: 2 µs
Wall time: 3.81 µs
[26]:
%%time
#* do this, it's cleaner, somewhat slower
x = 3
y = 4

x,y = y,x
CPU times: user 2 µs, sys: 0 ns, total: 2 µs
Wall time: 4.77 µs

Les conditions de if

Du moment qu’une condition est évaluée comme fausse, on passe à la ligne suivante.

[17]:
#! don't
from time import time
t = time()
abbreviations = ["cf.", "e.g.", "ex.", "etc.", "flg."]
for i in range(100000):
    for w in ("Mr.", "Hat", "is", "chasing", "."):
        if w in abbreviations and w[-1]=='.':
            pass
print(time() - t)
#* do
t = time()
abbreviations = ["cf.", "e.g.", "ex.", "etc.", "flg."]
for i in range(100000):
    for w in ("Mr.", "Hat", "is", "chasing", "."):
        if w[-1] == '.' and w in abbreviations:
            pass
print(time() - t)


0.0674431324005127
0.06275606155395508

To be continued, 2021-03-20