10. What are Type Hints
Traditional Python code
def twice(num):
return num * 2.0
using Type Hints
def twice(num: double) -> double:
return num * 2.0
PyCon Taiwan 2017 June 11th
11. Type Hints
using Type Hints
def twice(num: double) -> double:
return num * 2.0
C-language Code
double twice(double str) {
return str * 2.0;
}
PyCon Taiwan 2017 June 11th
14. Python2
Python 2.x series did not have a way to qualify function arguments and
return values, so many tools and libraries appeared to ll that gap.
def greeting(name):
return 'Hello ' + name
greet = greeting("Masato")
What is name ?
What does greeting return?
PyCon Taiwan 2017 June 11th
16. PEP 3107
adding Function annotations, both for parameters and return values,
are completely optional.You can write free text .
def compile(source: "something compilable",
filename: "where the compilable thing comes from",
mode: "is this a single statement or a suite?"):
the semantics were deliberately left unde ned.
PyCon Taiwan 2017 June 11th
17. PEP 484
def greeting(name: str) -> str:
return 'Hello ' + name
PEP-484 Type Hints
There has now been enough 3rd party usage for static type
analysis, that the community would bene t from a standardized
vocabulary and baseline tools within the standard library.
“
“
PyCon Taiwan 2017 June 11th
18. Point in PEP484
It’s not about code generation
It’s not going to affect how your compiler complies your code.
Your code can still break during run time after type checking.
It’s not going to make Python static-typed
Python will remain a dynamically typed language, and the authors
had no desire to ever make type hints mandatory, even by
convention.
“
“
PyCon Taiwan 2017 June 11th
19. return to the PEP484
def greeting(name: str) -> str:
return 'Hello ' + name
greet = greeting("Masato") # type: str # make greeting message!
Hmm , now I'd like to describe variables more easily
PyCon Taiwan 2017 June 11th
20. PEP 526
# PEP 484
def greeting(name: str) -> str:
return 'Hello ' + name
greet = greeting("Masato") # type: str # make greeting message!
# pep 526
def greeting(name: str) -> str:
return 'Hello ' + name
greet:str = greeting("Masato") # make greeting message!
PyCon Taiwan 2017 June 11th
22. What is the typing module
Module introduced when PEP 484 was implemented in 3.5
Provides python with frequently used types such as List, Dict
Make the data structure easier with namedtuple
from typing import List
a: List[int] = [1,2,3]
path: Optional[str] = None # Path to module sourde
PyCon Taiwan 2017 June 11th
23. NamedTuple
In Python 3.5(PEP 484)
Point = namedtuple('Point', ['x', 'y'])
p = Point(x=1, y=2)
In Python 3.6(PEP 526)
from typing import NamedTuple
class Point(NamedTuple):
x: int
y: int
p = Point(x=1, y=2)
PyCon Taiwan 2017 June 11th
26. How to write
I talk about PEP526 style
def greeting(name: str) -> str:
return 'Hello ' + name
greet: str = greeting("Masato")
PyCon Taiwan 2017 June 11th
27. difference of PEP484 and PEP526
# pep 484
child # type: bool # cannot allow
if age < 18:
child = True # type: bool # It's OK
else:
child = False # type: bool # It's OK
# pep 526
child: bool # OK
if age < 18:
child = True # No need to Write bool
else:
child = False
PyCon Taiwan 2017 June 11th
28. backward compatibility
# We can write pep484 style code in 3.6 backward compatiblity
hour = 24 # type: int
# PEP 526 style
hour: int; hour = 24
hour: int = 24
PyCon Taiwan 2017 June 11th
29. Attention points
PEP3107 style is also OK
>>> alice: 'well done' = 'A+'
>>> bob: 'what a shame' = 'F-'
>>> __annotations__
{'alice': 'well done', 'bob': 'what a shame'}
But let's use for Type Hints as much as possible for the future.
PyCon Taiwan 2017 June 11th
30. How to get Type Hints Info
Q. where is variable annotation
A. at __annotaitons__
>>> answer:int = 42
>>> __annotations__
{'answer': <class 'int'>}
PyCon Taiwan 2017 June 11th
31. Attention
We can only nd Class variables .
>>> class Car:
... stats: ClassVar[Dict[str, int]] = {}
... def __init__(self) -> None:
... self.seats = 4
>>> c: Car = Car()
>>> c.__annotations__
{'stats': typing.ClassVar[typing.Dict[str, int]]}
# only ClassVar!
We cannot get instance's variables!
PyCon Taiwan 2017 June 11th
33. Bene ts
Code Style
code completion
statistic type analysis
Our story
PyCon Taiwan 2017 June 11th
34. Code Style
Simple is best
Explicit is better than Implicit.
def greeting(name: str) -> str:
return 'Hello ' + name
We can check this by Type Hints
def greeting(name: str) -> str:
return 42
PyCon Taiwan 2017 June 11th
35. Code Completion
We can use code completion in
Editor
Visual Studio code
PyCharm(IntelliJ)
PyCon Taiwan 2017 June 11th
41. mypy
$ pip install mypy
# if you use Python 2.7 & 3.2-3.4
$ pip install typing
PyCon Taiwan 2017 June 11th
42. mypy example
code(example.py)
from typing import NamedTuple
class Employee(NamedTuple):
name: str
id: int
emp: Employee = Employee(name='Guido', id='x')
run
$ mypy --python-version 3.6 example.py
example.py:16: error: Argument 2 to "Employee" has incompatible type
"str"; expected "int"
PyCon Taiwan 2017 June 11th
43. mypy can use in Python2
class MyClass(object):
# For instance methods, omit `self`.
def my_method(self, num, str1):
# type: (int, str) -> str
return num * str1
def __init__(self):
# type: () -> None
pass
x = MyClass() # type: MyClass
PyCon Taiwan 2017 June 11th
45. Continuous Integration
we can run mypy on CI systems
we can get results
If you develop in a team, there are many bene ts
ex: If someone issues a pull request for your project, you can
review their code
PyCon Taiwan 2017 June 11th
48. Bene ts for me
We use Fabric for deployment
But it is for Only Python2
Python2 will nished at 2020(Tokyo Olympic Year)
We thought we should convert Python2 to Python3
PyCon Taiwan 2017 June 11th
49. We want to use Python3
We use fabric3
It's fabric for Python3
https://pypi.python.org/pypi/Fabric3
We try to check this, That's good for run
PyCon Taiwan 2017 June 11th
50. We use Python3 & Fabric3 & mypy
We use TypeHints for rewriting our code
We got it! -> Only 2days
We deploy the new version of Out App every week.
beta version every day!
PyCon Taiwan 2017 June 11th
51. Those are the Bene ts of Type Hints
PyCon Taiwan 2017 June 11th
52. Today I introduced, and talked about
usage and bene ts of Type Hints
PyCon Taiwan 2017 June 11th
53. I hope you can try using Type Hinting
from today!
PyCon Taiwan 2017 June 11th