TypedDict Introspection For Config Dicts
TypedDict records which config keys are required versus optional, and __required_keys__ plus __optional_keys__ let runtime code inspect that contract.
Code
from typing import NotRequired, TypedDict, is_typeddict
class AppConfig(TypedDict):
host: str
port: int
token: NotRequired[str]
class FeatureFlags(TypedDict, total=False):
dark_mode: bool
beta_queue: bool
# 运行时它仍是普通 dict:TypedDict 不做校验,只服务类型检查器与文档
config: AppConfig = {"host": "0.0.0.0", "port": 8080}
print("runtime type:", type(config).__name__, sorted(config))
# 键约束本身可以被程序内省:required 与 optional 都在类属性里
print("required:", sorted(AppConfig.__required_keys__))
print("optional:", sorted(AppConfig.__optional_keys__))
print("flags :", sorted(FeatureFlags.__optional_keys__))
print("is_typeddict(AppConfig):", is_typeddict(AppConfig))
# 类型不匹配运行时也不报错:校验要交给 pydantic 这类运行时方案
config["port"] = "8080/tcp"
print("unchecked at runtime:", config["port"])Output
Captured from a sandboxed run of this snippet in the build pipeline.
runtime type: dict ['host', 'port']
required: ['host', 'port']
optional: ['token']
flags : ['beta_queue', 'dark_mode']
is_typeddict(AppConfig): True
unchecked at runtime: 8080/tcpHow the snippet works
TypedDict Introspection For Config Dicts keeps everything in the classes AppConfig and FeatureFlags.
Everything operates on top-level bindings: config.
Using it
The run emits 5 labeled sections — runtime type:, required:, optional:, is_typeddict(AppConfig):, unchecked at runtime: — one per step.
Key statements
config: AppConfig = {"host": "0.0.0.0", "port": 8080}
Interactive Tools for This Topic
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
FAQ
- Are there third-party dependencies?
- No. The dependency list is empty; the code stays inside the standard library. Its state lives in module-level bindings: `config`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.