Skip to content

Latest commit

 

History

History
88 lines (53 loc) · 1.35 KB

File metadata and controls

88 lines (53 loc) · 1.35 KB

Type Hints in Python

Learned about this today, so I'm organizing it!

Reference: python docs



Before getting started

  • The Python runtime does not enforce type annotations on functions or variables

    • You need to use an IDE or type checker to verify them
  • You can provide type hints to indicate types when using methods



Function Annotations

docs

  • Function annotations can be used for Parameters and return values, but they are not mandatory!
  • Function annotations can be used to provide type checking
    • However, Lambda does not support annotations!

Syntax

1. Parameters

ex1) parameter

def foo(a: expression, b: expression = 2):
  ...

ex2) excess parameter ( *args, **kwargs )

def foo(*args: expression, **kwargs: expression):
    ...

2. Return Values

ex)

def sum() -> expression:
  ...



+

Type aliases

: Additionally, you can also use aliases!

ex)

from typing import List
Vector = List[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])