Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python static typing does not work

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 ?

like image 325
Aymen Gasmi Avatar asked May 30 '16 13:05

Aymen Gasmi


2 Answers

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.

like image 73
Nick Matteo Avatar answered Sep 29 '22 11:09

Nick Matteo


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
like image 31
chrislessard Avatar answered Sep 29 '22 13:09

chrislessard