Ver a proveniência

python 10

master
Dimitri Merejkowsky há 5 anos
ascendente
cometimento
a83f05efea
3 ficheiros alterados com 134 adições e 1 eliminações
  1. +1
    -0
      notes.md
  2. +1
    -1
      sessions/Makefile
  3. +132
    -0
      sessions/python-10.md

+ 1
- 0
notes.md Ver ficheiro

@@ -26,6 +26,7 @@ Ce fichier contient diverses notes utiles à la préparation des futurs cours.
* slices takes a step too [::-1] -> reverse
* with: contextmanager, ContextDecorator
* short circuit in if: `if a is not None and a.b == 42`
* splat operator, *args, **kwags, keyword-only

## big stuff



+ 1
- 1
sessions/Makefile Ver ficheiro

@@ -1,4 +1,4 @@
all: python-09.pdf
all: python-10.pdf

%.pdf: %.md
pandoc -t beamer $< -o $@

+ 132
- 0
sessions/python-10.md Ver ficheiro

@@ -0,0 +1,132 @@
% Programmation avec Python (chapitre 10)
% Dimitri Merejkowsky

\center \huge Rappels

* string formatting (%, .format(), f"")
* abstract base classes


\center \huge Exceptions

* Examples:
* division par zéro
* dépassement d'un tableau
* clé non trouvée dans un dico
* opération entre types incompatibles
* le fichier n'existe pas
* la variable n'existe pas

* les backtraces
* comment les lire
* y a un sens!

```python
def une_fonction():
return 1 / 0

def une_autre_fonction():
une_fonction()

une_autre_fonction()
```



```python
def une_fonction(diviseur):
return 1 / diviseur

def une_autre_fonction():
une_fonction(diviseur=0)

une_autre_fonction()
```

# Lever une exception

```python
def retirer_somme(compte, montant):
solde = ...
if montant >= solde:
raise ValueError("montant supérieur au solde!")
```

# Attraper une exception

* Quand c'est pas le bon type, ben ça throw quand même
* On peut mettre plusieurs blocs de `catch`
* On peut attraper plusieurs exceptions d'un coup

Attention aux bare except

# Hiérarchies

À connaître
À utiliser si vous faites une librairie.

# finally, else

# WBYL et EAFP

Watch Before You Leap
Easier to Ask for Forgiveness than Permission

fichiers encore:

```python
if exists():
if pas_un_dossier():
if j_ai_les_droits_en_lecture():
open(filename):
```

```python
try:
open(filename):
catch IOError:
...
```


# avec with


# attention a ou vous mettez except

```python
if truc:
if machin:
for bidule in chose:
raise MyError("kaboom!")
````

```python
if truc:
if machin:
try:
for bidule in chose:
raise MyError("kaboom!")
except:
...

```


```python
if truc:
try:
if machin:
for bidule in chose:
raise MyError("kaboom!")
except:
...

````


# Accédér aux détails de l'exceptions

* Avec `as`
* Attrribut `args`
* Parfois d'autres atttributs (voir la doc)