Skip to content

Instantly share code, notes, and snippets.

@masahitojp
Last active June 7, 2017 04:47
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/57ef0ad5d464dadeacd2ac62d3538575 to your computer and use it in GitHub Desktop.
Save masahitojp/57ef0ad5d464dadeacd2ac62d3538575 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


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


Body -delete

    1. Introduction
    1. Usage
    1. Benefits

Introduction - delete

  • What is Type Hinting?
  • History
    • PEP 3123
    • PEP 484
    • PEP 526
  • modules

Usage -delete

  • How to write
  • What has changed?
  • Background

Benefits -delete

  • 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

Introduction


What is Type Hints

  • Traditionary Python code
def twice(num):
    return num * 2.0
  • use Type Hint
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 History.

PEP implement
3107 Python 3.0
484 Python 3.5
526 Ptyhon 3.6

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?

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 code

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

greet = greeting("Masato") # type: str

Hmm , now I'd like to explain variables more easily😟


PEP 526

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

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

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

Usage


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

# pep 526
child: bool # OK
if age < 18:
    child = True
else:
    child = False

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

implementation at Python

where is variable annotation

at __annotaitons__

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

Attention

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!

Attention

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.


Type Hints based on typing module


Benefits


Benefits

  • Code Style
  • IDE
  • statistic type analysis

Code Style

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

We can check this by Type Hints

def greeting(name: str) -> str:
    return 42

IDE

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

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"

--

mypy for Python3.6

  • We can use!(PEP526 style)

CI

  • Jenkins
  • Github + Travis CI
  • Github + CircleCi

Github + Travis CI

  • we can run mypy
  • we can get results
    • If you develop by team, You can get many benefits

That's all


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


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