Sujet : Re: Signature d'une fonction (was: [SOLUTION] Tri de crêpes)
De : ram (at) *nospam* zedat.fu-berlin.de (Stefan Ram)
Groupes : fr.comp.lang.pythonDate : 05. Dec 2024, 22:59:24
Autres entêtes
Organisation : Stefan Ram
Message-ID : <test-20241205225548@ram.dialup.fu-berlin.de>
References : 1 2 3 4 5 6 7 8
Olivier Miakinen <om+
news@miakinen.net> a écrit ou cité :
Je viens d'essayer en 3.8.10. La syntaxe est accept?e mais ?a ne g?n?re aucune
erreur si je fais un appel contredisant la signature.
def test(machin:str, truc:int) -> int:
... print(machin, truc)
... return machin
...
test(3, "7")
3 7
3
test(3, "aed")
3 aed
3
test("def", "aed")
def aed
'def'
Ouais, c'est ouf !
L'idée derrière tout ça, c'est que Python veut rester une
langue sans typage statique de base. On peut voir les types
comme des commentaires, ou utiliser des outils supplémentaires
pour vérifier les types.
Un exemple, c'est « mypy ». Généralement, on l'appelle comme un
script externe, mais des fois je le lance directement depuis mon
script Python. Voici un bout de code avec la sortie :
Code source :
from mypy import api; o = api.run([__file__])
if( o[ -1 ]):
for i in o:
print( 'mypy:', i )
del api
def test(machin:str, truc:int) -> int:
print(machin, truc)
return machin
test(3, "7")
test(3, "aed")
test("def", "aed")
Sortie :
mypy: test.py:9: error: Incompatible return value type (got "str", expected "int") [return-value]
test.py:11: error: Argument 1 to "test" has incompatible type "int"; expected "str" [arg-type]
test.py:11: error: Argument 2 to "test" has incompatible type "str"; expected "int" [arg-type]
test.py:13: error: Argument 1 to "test" has incompatible type "int"; expected "str" [arg-type]
test.py:13: error: Argument 2 to "test" has incompatible type "str"; expected "int" [arg-type]
test.py:15: error: Argument 2 to "test" has incompatible type "str"; expected "int" [arg-type]
Found 6 errors in 1 file (checked 1 source file)
mypy:
mypy: 1
3 7
3 aed
def aed