Gradual Typing in Python

Types of Typing

  • Static: type known at compile time
  • Dynamic: type determined at run time

The Benefits of Static Typing

http://ttendency.cs.ucl.ac.uk/projects/type_study/

The Third Type: Gradual

Python 3.5

The typing module


import json
import requests

def upload(data):
    requests.post('http://example.com', json=data)

mydata = json.dumps({'foo': 'bar'})
upload(mydata)
          

import json
import requests
from typing import Mapping, TypeVar

T = TypeVar('T')

def upload(data: Mapping[str, T]):
    requests.post('http://example.com', json=data)

mydata = json.dumps({'foo': 'bar'})
upload(mydata) # static checker will complain
          

MyPy: the Static Checker

Run this as part of test suite/CI