Type a Config Function
Intermediate · Write the code · from Python Type Hints: Add Types, Generics, and the typing Module
From the lesson: How Do You Type Lists, Dicts, and Tuples?
Plain list, dict, and tuple annotations don't tell you what's inside the collection. The typing module lets you specify element types for precise annotations.
Read this part of the lessonWrite a function get_config that takes a Dict[str, str] of config values and an Optional[str] default value. It should look up a key and return the value if found, or the default if not.
Type-hint everything: parameters, return type, and the config variable.
config = {'host': 'localhost', 'port': '8080'}
print(get_config(config, 'host')) # localhost
print(get_config(config, 'debug', 'off')) # off
print(get_config(config, 'missing')) # Nonefrom typing import Dict, Optional
def get_config(data, key, default=None):
# Add type hints and implement
pass
config = {'host': 'localhost', 'port': '8080'}
print(get_config(config, 'host'))
print(get_config(config, 'debug', 'off'))
print(get_config(config, 'missing'))
More Type Hints exercises
- Add Type Hints to a FunctionIntermediate
- Predict the Output with Type HintsIntermediate
- Type a Higher-Order FunctionIntermediate
- Add Runtime Type CheckingIntermediate
- Type a Data Processing FunctionAdvanced
All Python exercises · 50 practice problems · Advanced Python quiz