<script async src="//embedr.flickr.com/assets/client-code.js" charset="utf-8"></script>
- What is Type Hints
- Hisory
- typing module
- Traditional Python code
def twice(num):
return num * 2.0
- use Type Hints
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 a three-step history.
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?
PEP | implement |
---|---|
3107 | Python 3.0 |
484 | Python 3.5 |
526 | Ptyhon 3.6 |
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 # make greeting message!
Hmm , now I'd like to explain variables more easily
# 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!
- 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(PEP 484)
Point = namedtuple('Point', ['x', 'y'])
p = Point(x=1, y=2)
print(p.z) # Error: Point has no attribute 'z'
In Python 3.6(PEP 526)
from typing import NamedTuple
class Point(NamedTuple):
x: int
y: int
- How to write
- How to get Type Hints Info
I talk about PEP526 style
def greeting(name: str) -> str:
return 'Hello ' + name
greet: str = greeting("Masato")
# 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
# We can write pep484 style in 3.6 __backward compatiblity__
hour = 24 # type: int
# PEP 526 style
hour: int; hour = 24
hour: int = 24
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 possible for the future.
>>> answer:int = 42
>>> __annotations__
{'answer': <class 'int'>}
We can find only 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 variable!
- Code Style
- code completion
- statistic type analysis
- Our story
- 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
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
- We can use!(PEP526 style)
$ pip install mypy-lang
- code(example.py)
from typing import NamedTuple
class Employee(NamedTuple):
id: int
name: str
employee = Employee(name='Guido', id='x')
- run
$ mypy --fast-parser --python-version 3.6 example.py
example.py:16: error: Argument 2 to "Employee" has incompatible type "str"; expected "int"
- Jenkins
- Github + Travis CI
- Github + CircleCi
- we can run mypy on CI systems
- we can get results
- If you develop by team, You can get many benefits
- ex: If someone provide Pull Request for Your Project, you can check them codes.
- (red graphic)
- (green graphic)
- We use Fabric for deploy
- But it is for Only Python2
- Python2 will finished at 2020(Tokyo Olympic Year)
- We thout convert Python2 to Python3
- We use fabric3
- It's fabric for Python3
- We try to check this, That's good for run
- We use TypeHints for converting the code
- We got it!
- Only 1days
- We deploy the new version of Out App every week.
<script async src="//embedr.flickr.com/assets/client-code.js" charset="utf-8"></script>