What are `TypedDict` and `Protocol`, and when are they useful?
AdvancedConceptLanguage essentials & functions
Answer
TypedDicttypes a dict with known string keys, perfect for API payloads you keep as dicts:class Tag(TypedDict): Key: str; Value: str.boto3-stubsuses TypedDicts for every boto3 response.Protocolis structural typing ("anything with a.describe_instances()method"), so you can type an injected client without depending on a concrete class, which makes fakes in tests type-check cleanly.
class SupportsSend(Protocol):
def send(self, msg: str) -> None: ...
More on Language essentials & functions
Why is Python the default scripting language in so many DevOps teams, and where would you not use it?BeginnerWhat is the difference between mutable and immutable types? Give examples.BeginnerWhat does assignment do in Python, and how do shallow and deep copies differ?BeginnerExplain the mutable default argument bug and how to fix it.IntermediateWhat is the difference between `==` and `is`?BeginnerWhat values are "falsy" in Python, and why does it matter in scripts?Beginner