Skip to content

Instantly share code, notes, and snippets.

@masahitojp
Last active June 8, 2017 13:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save masahitojp/eb6490aeadcd7c1658233a99fac9bea8 to your computer and use it in GitHub Desktop.
Save masahitojp/eb6490aeadcd7c1658233a99fac9bea8 to your computer and use it in GitHub Desktop.

The Benefit of Type Hints


Masato Nakamura @ Nulab From Japan

Coffee<script async src="//embedr.flickr.com/assets/client-code.js" charset="utf-8"></script>


What is Nulab


We provide Communication-Wares.

75%


My Goal

You can try Type Hints from today!


Not to talk about today

Details


Today I will talk about the Introduction, Usage and Benefits of Type Hints


Introduction


Introduction

  • What is Type Hints
  • Hisory
  • typing module

What is Type Hints

  • Traditional Python code
def twice(num):
    return num * 2.0
  • use Type Hints
def twice(num: double) -> double:
    return num * 2.0

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;
}

History


History

Type Hints has a three-step history.


Python2

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?

History

PEP implement
3107 Python 3.0
484 Python 3.5
526 Ptyhon 3.6

PEP 3107

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.


PEP 484

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

Non Goal for PEP484

Python will remain a dynamically typed language, and the authors have no desire to ever make type hints mandatory, even by convention.


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 explain variables more easily


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!

typing module


What is typing module

  • 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

Usage


Usage

  • How to write
  • How to get Type Hints Info

How to write

I talk about PEP526 style

def greeting(name: str) -> str:
    return 'Hello ' + name

greet: str = greeting("Masato")

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


backward compatibility

# We can write pep484 style in 3.6 __backward compatiblity__
hour = 24 # type: int

# PEP 526 style
hour: int; hour = 24


hour: int = 24

Attentions

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.


How to get Type Hints Info

Q. where is variable annotation�

A. at __annotaitons__

>>> answer:int = 42
>>> __annotations__
{'answer': <class 'int'>}

Attentions

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!


Benefits


Benefits

  • Code Style
  • code completion
  • statistic type analysis
  • Our story

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

Code Completion

We can code completion in

  • Editor
    • Visual Studio code
  • PyCharm(IntelliJ)

example


statistic type analysis


statistic type analysis

  • for check variable type(no run code)
  • python has some tools
    • mypy
    • pytypes (not talk)

mypy


mypy

$ pip install mypy-lang

mypy example

  • 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"

CI

  • Jenkins
  • Github + Travis CI
  • Github + CircleCi

CI

  • 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.

example(error)

  • (red graphic)

example(success)

  • (green graphic)

Benefits for me

  • 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 wanto to use Python3

  • We use fabric3
    • It's fabric for Python3
  • We try to check this, That's good for run

We use Python3 & Fabric3 & mypy

  • We use TypeHints for converting the code
  • We got it!
  • Only 1days
  • We deploy the new version of Out App every week.

It is the Story of our Benefits of Type Hints


Today I talked about the Introduction, Usage and Benefits of Type Hints


I hope you can try Type Hinting from today!

zen cat<script async src="//embedr.flickr.com/assets/client-code.js" charset="utf-8"></script>


Question?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment