Skip to content

Instantly share code, notes, and snippets.

@asmaier
Last active January 16, 2018 17:18
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 asmaier/f2577460efa6270bdfc47738becc80a8 to your computer and use it in GitHub Desktop.
Save asmaier/f2577460efa6270bdfc47738becc80a8 to your computer and use it in GitHub Desktop.
Minimal overview of Python Type Hints

Python Type Hints

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

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

  • 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!
  • 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!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment