Skip to content

Instantly share code, notes, and snippets.

@tafaust
Created February 12, 2022 08:24
Show Gist options
  • Save tafaust/1e4863f7f668f4af33e91d76571aa213 to your computer and use it in GitHub Desktop.
Save tafaust/1e4863f7f668f4af33e91d76571aa213 to your computer and use it in GitHub Desktop.
Python run time vs development time dict key check
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
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!