mypy
是否有可能在Python3.6+
它们的任何扩展中指定我的函数可以将任何 dict 作为参数,只要它具有特定的键?如果有一个假设类型Record
For eg
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
因此,静态分析应报告以下内容
full_name(valid_dict) # => works
full_name(big_and_valid_dict) # => works
full_name(invalid_dict1) # => error
full_name(invalid_dict2) # => error