Last active
July 1, 2021 17:26
-
-
Save harsh183/f834d216f75faecc301f2e8e4cc90863 to your computer and use it in GitHub Desktop.
A small exploration with mypy and python type annotations.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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)) |
The output
3
16
6.25
64
0.125
None
1
MIT License
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Before running it
To type check
To run (as normal basically)