1

Is it possible in mypy or Python3.6+ or in any of their extensions to specify that my function can take any dict as a parameter as long as it has specific keys in it? If there is an hypothetical type Record For e.g.

def full_name(my_dict: Record[first_name: str, last_name: str]) -> str:
  return my_dict['last_name'] + ',' + my_dict['first_name']

valid_dict = {'first_name': 'John', 'last_name': 'Doe'}
big_and_valid_dict = {'first_name': 'Matt', 'last_name': 'Legi', 'age': 32}
invalid_dict1 = {'first_name': 'BadName'} # No 'last_name' key
invalid_dict2 = {'no_name': 'NoName'} # none of the specified keys

So, static analysis should report the following as

full_name(valid_dict) # => works
full_name(big_and_valid_dict) # => works
full_name(invalid_dict1) # => error
full_name(invalid_dict2) # => error
RAbraham
  • 5,096
  • 4
  • 32
  • 60
  • You could probably do this with a decorator. [This post](https://stackoverflow.com/questions/15299878/how-to-use-python-decorators-to-check-function-arguments) has some suggestions on how to check the types of function parameters, not quite the same, but probably a good starting point. – Luke Smith Nov 02 '17 at 20:42
  • 1
    @LukeSmith: That's a runtime check, not type hinting. – user2357112 supports Monica Nov 02 '17 at 20:52
  • 1
    Have you seen [`TypedDict`](https://mypy.readthedocs.io/en/latest/kinds_of_types.html#typeddict)? It seems close to what you're looking for – Patrick Haugh Nov 02 '17 at 21:13
  • Ya, I looked at `TypedDict`. I don't think the above is possible with it with my reading of the docs. – RAbraham Nov 02 '17 at 21:40
  • Possible duplicate of [Dictionary with some mandatory keys as function input](https://stackoverflow.com/questions/21014761/dictionary-with-some-mandatory-keys-as-function-input) – Stevoisiak Feb 28 '18 at 20:29

0 Answers0