I found out that Python is intending to support static typing, but it still in beta phase. I tried the following code with python 3.4.3:
def somme(a: int, b: int) -> int:
return a + b
the syntax is supported but I did not get the expected result. if I type somme('1', '3')
I get 13, while I should get TypeError
exception saying int variable expected
.
Has anyone an idea why it's not working ?
The function annotations there are annotations, nothing more. They're documentation about intended usage. Like it says in PEP 3107, the mechanism provides a single, standard way to specify function parameters and return values, replacing a variety of ad-hoc tools and libraries.
But as it goes on to say:
Function annotations are nothing more than a way of associating arbitrary Python expressions with various parts of a function at compile-time.
By itself, Python does not attach any particular meaning or significance to annotations. Left to its own, Python simply makes these expressions available as described in Accessing Function Annotations below.
PEP 484 adds more conventions and tools for using these annotations to mark types, adopted in Python 3.5. But still there is no runtime checking in the language itself: it "includes support for off-line type checkers such as mypy".
That is, after using these annotations, you can run third-party type checkers to check if your code adheres to the annotated types. Building these annotations into the language should make it easier for various IDEs to provide this service.
In reality, you aren't supposed to get static typing here. The code you wrote is actually a form of easy documentation and "type hinting", as explained here. To quote that PEP:
While these annotations are available at runtime through the usual annotations attribute, no type checking happens at runtime . Instead, the proposal assumes the existence of a separate off-line type checker which users can run over their source code voluntarily. Essentially, such a type checker acts as a very powerful linter. (While it would of course be possible for individual users to employ a similar checker at run time for Design By Contract enforcement or JIT optimization, those tools are not yet as mature.)
So in other words, it was developed to support a third party library that will actually do the checking for you. I've never bothered with static typing in Python, although a friend of mine often uses MyPy to achieve it. This might be what you're looking for.
EDIT:
installation : MyPy can be installed using pip:
pip install mypy-lang
Usage : you can type-check your program as follow:
~$ mypy my_script.py
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With