<script async src="//embedr.flickr.com/assets/client-code.js" charset="utf-8"></script>
-
- Introduction
-
- Usage
-
- Benefits
- What is Type Hinting?
- History
- PEP 3123
- PEP 484
- PEP 526
- modules
- How to write
- What has changed?
- Background
- Code Style
- Simple is best
- Explicit is better than Implicit.
- Editor
- Code Completion
- static analysis
- use with command line
- use with Editor
- use with CI
- Traditionary Python code
def twice(num):
return num * 2.0
- use Type Hint
def twice(num: double) -> double:
return num * 2.0
- using Type Hints
def twice(num: double) -> double:
return num * 2.0
C-language Code
double twice(double str) {
return str * 2.0;
}
Type Hints has History.
PEP | implement |
---|---|
3107 | Python 3.0 |
484 | Python 3.5 |
526 | Ptyhon 3.6 |
Python 2.x series did not have a way to qualify function arguments and return values, so many tools and libraries appeared to fill that gap.
def greeting(name):
return 'Hello ' + name
greet = greeting("Masato")
- What is
name
? - What does
greeting
return values?
add 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 undefined.
There has now been enough 3rd party usage for static type analysis that the community would benefit from a standard vocabulary and baseline tools within the standard library.
def greeting(name: str) -> str:
return 'Hello ' + name
Python will remain a dynamically typed language, and the authors have no desire to ever make type hints mandatory, even by convention.
def greeting(name: str) -> str:
return 'Hello ' + name
greet = greeting("Masato") # type: str
Hmm , now I'd like to explain variables more easily😟
from typing import List
# pep 484
a = [1,2,3] # type: List[int]
# We should add *comments*
path = None # type: Optional[str] # Path to module source
# pep 526
a: List[int] = [1,2,3]
path: Optional[str] = None # Path to module sourde
- Module entered when PEP 484 was implemented in 3.5 - For providing python with frequently used types such as List, Dict
- Make the data structure easier as
namedtuple
from typing import List
a: List[int] = [1,2,3]
path: Optional[str] = None # Path to module sourde
- NamedTuple
In Python 3.5
Point = namedtuple('Point', ['x', 'y'])
p = Point(x=1, y=2)
print(p.z) # Error: Point has no attribute 'z'
In Python 3.6
from typing import NamedTuple
class Point(NamedTuple):
x: int
y: int
I talk about PEP526 style
def greeting(name: str) -> str:
return 'Hello ' + name
greet: str = greeting("Masato")
# pep 484
child # type: bool # cannot allow
# pep 526
child: bool # OK
if age < 18:
child = True
else:
child = False
# We can write pep484 style in 3.6(backward compatiblity!
hour = 24 # type: int
# PEP 526 style
hour: int; hour = 24
hour: int = 24
at __annotaitons__
>>> answer:int = 42
>>> __annotations__
{'answer': <class 'int'>}
We can find Class variables
.
ignored instance variable
>>> 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!
PEP3107 style
>>> 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 possible for the future.
- Code Style
- IDE
- statistic type analysis
def greeting(name: str) -> str:
return 'Hello ' + name
We can check this by Type Hints
def greeting(name: str) -> str:
return 42
We can code completion in
- Editor
- Visual Studio code
- PyCharm(IntelliJ)
- for check variable type(no run code)
- python has some tools
- mypy
- pytypes (not talk)
- https://github.com/python/mypy
- made by man named JukkaL & Guido
- can output report
from typing import Dict, NamedTuple
class Car:
stats: Dict[str, int] = {}
def __init__(self) -> None:
self.seats = 4
class Employee(NamedTuple):
name: str
id: int
c: Car = Car()
# print(c.__annotations__)
employee = Employee(name='Guido', id='x')
mypy --fast-parser --python-version 3.6 example.py
example.py:16: error: Argument 2 to "Employee" has incompatible type "str"; expected "int"
--
- We can use!(PEP526 style)
- Jenkins
- Github + Travis CI
- Github + CircleCi
- we can run mypy
- we can get results
- If you develop by team, You can get many benefits
<script async src="//embedr.flickr.com/assets/client-code.js" charset="utf-8"></script>