Python Type Hints

Overview

  • Type after variable
  • Problem: IDE cannot suggest variable name based on type

Primitives

From

// primitive function
def uga_uga(text):

to

def uga_uga(text: str) -> int:
"""
Very primitive AI.
:param text: Input text
:return: Number parsed by primitive AI
"""

Not so primitives

Tuples, Dicts, etc…

from typing import Tuple

def returns_tuple(input: str) -> Tuple[str, str]:

Void method

def i_have_side_effects(path: str) -> None:

Complex types

import pyspark
from pyspark.sql.column import Column

def do_stuff(sc: pyspark.SparkContext, path: str) -> Column:

Default value

  • Confusing syntax at first

From

def dirty_function(cleanup=True):

to

def dirty_function(cleanup: bool=True) -> Something:

The value of cleanup is True not the value of bool! Another disadvantage of types after variable name.

Conclusion 1

  • Cool for final documentation
  • Only type hints, but no accessibility and changeability (const vs. variable): This is not a complete compiler!
  • How to express contracts like
    • This function doesn’t accept None
    • This function does never return None
    • This function can throw exception ABC and DEF.
    • def convert(year, month, day) with year > 1970, 1 < month < 12, and day = 31, 30, 29 or 28 ?
    • Don’t program your rocket’s software in Python, use ADA!

Conclusion 2

  • wouldn’t C/Java style be better?
def Tuple[str, str] returns_tuple(str:input = "default") :
  • Even with a wrong type hint your code can still run.
    • How to maintain type hints, when refactoring the code?
    • Regularly run static code analysis to detect inconsistencies: like a compiler!

End

Original presentation on github gist: