Sujet : Re: Python does what?
De : jp (at) *nospam* python.invalid (Python)
Groupes : fr.comp.lang.pythonDate : 19. Apr 2025, 17:12:53
Autres entêtes
Organisation : Nemoweb
Message-ID : <qkXiBsNSqQznGMXUYakD1nUMo5w@jntp>
References : 1 2
User-Agent : Nemo/1.0
Le 11/03/2025 à 21:18, Thomas Alexandre a écrit :
Le Tue, 11 Mar 25 18:47:54 +0000, Python a écrit :
def what():
.. try:
.. return 12
.. finally:
.. return 42 ..
what()
? ? ?
1. Essayer de prévoir
42
2. Vérifier
```
The return value of a function is determined by the last return statement executed. Since the finally clause always executes, a return statement executed in the finally clause will always be the last one executed
```
https://docs.python.org/3/reference/compound_stmts.html#finally-clause
Oui, c'est totalement contre-intuitif - particulièrement dans cet exemple.
$ cat what.py #!/usr/bin/env python3
try:
exit(0)
finally:
exit(42)
$ ./what.py ; echo $?
42