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 
5
  • You could probably do this with a decorator. This post has some suggestions on how to check the types of function parameters, not quite the same, but probably a good starting point. Commented Nov 2, 2017 at 20:42
  • 1
    @LukeSmith: That's a runtime check, not type hinting. Commented Nov 2, 2017 at 20:52
  • 1
    Have you seen TypedDict? It seems close to what you're looking for Commented Nov 2, 2017 at 21:13
  • Ya, I looked at TypedDict. I don't think the above is possible with it with my reading of the docs. Commented Nov 2, 2017 at 21:40
  • Possible duplicate of Dictionary with some mandatory keys as function input Commented Feb 28, 2018 at 20:29

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.