Created
February 12, 2022 08:24
-
-
Save tafaust/1e4863f7f668f4af33e91d76571aa213 to your computer and use it in GitHub Desktop.
Python run time vs development time dict key check
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
from typing import TypedDict | |
class Movie(TypedDict): | |
name: str | |
year: int | |
def foo(movie_params: Movie): | |
pass # do your thing | |
foo({'name': 'John Doe', 'year': 1337}) # all good during development time | |
foo({'name': 'John Doe', 'yar': 1337}) # Expected type 'Movie', got 'dict[str, Union[str, int]]' instead |
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
from typing import Dict, Any | |
def foo(movie_params: Dict[str, Any]): | |
allowed_movie_keys = {'name', 'year'} | |
if not allowed_movie_keys >= movie_params.keys(): | |
print('Runtime Error!') | |
else: | |
print('Success!') | |
foo({'name': 'John Doe', 'year': 1337}) | |
# Success! | |
foo({'name': 'John Doe', 'yar': 1337}) # typo in year | |
# Runtime Error! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://gist.github.com/tahesse/1e4863f7f668f4af33e91d76571aa213#file-run_time_check-py-L6-L7 refers to https://docs.python.org/3.8/library/stdtypes.html#frozenset.issuperset