Skip to content

Instantly share code, notes, and snippets.

@harsh183
Last active July 1, 2021 17:26
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 harsh183/f834d216f75faecc301f2e8e4cc90863 to your computer and use it in GitHub Desktop.
Save harsh183/f834d216f75faecc301f2e8e4cc90863 to your computer and use it in GitHub Desktop.
A small exploration with mypy and python type annotations.
# Simple script I put together showing mypy in action
# standard type annotations - we can give arguments a type and expect a return type
def add(x: int, y: int) -> int:
return x + y
print(add(1, 2))
# we can let it pick within a list of types
from typing import Union
def square(x: Union[int, float]) -> Union[int, float]:
return x * x
print(square(4))
print(square(2.5))
# generics - achieved via
# so we can achieve what sum types did but match everything too
from typing import TypeVar
T = TypeVar('T', int, float)
def cube(x: T) -> T:
return x*x*x
print(cube(4))
print(cube(0.5))
# y: int = cube(0.5) # this throws an error because float has to match with float
# optional - can be None or proper result
from typing import Optional
def factorial(x: int) -> Optional[int]:
if (x < 0):
return None
elif (x == 0 or x == 1):
return 1
else:
return factorial(x - 1)
print(factorial(-1))
print(factorial(10))
@harsh183
Copy link
Author

harsh183 commented Oct 3, 2019

Before running it

pip3 install mypy

To type check

mypy mypy-example.py

To run (as normal basically)

python3 mypy-example.py

@harsh183
Copy link
Author

harsh183 commented Oct 3, 2019

The output

3
16
6.25
64
0.125
None
1

@harsh183
Copy link
Author

MIT License

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment