TypedDict Types Keys With NotRequired

Describe dict payloads at the type level with TypedDict: required keys stay mandatory, NotRequired keys are consumed behind membership checks.

PythonData Integrity

Code

pythonsnippet
28 lines
from typing import NotRequired, TypedDict


class WebhookPayload(TypedDict):
    event: str
    delivery_id: str
    # NotRequired 键允许缺席:signature 只在重试事件里出现
    signature: NotRequired[str]


def route(payload: WebhookPayload) -> str:
    target = payload['event']
    if 'signature' in payload:
        target += ' (signed ' + payload['signature'] + ')'
    return target


first: WebhookPayload = {
    'event': 'invoice.paid',
    'delivery_id': 'd-771',
}
retry: WebhookPayload = {
    'event': 'invoice.paid',
    'delivery_id': 'd-771',
    'signature': 'sha256=9f2c',
}
print(route(first))
print(route(retry))

Output

Captured from a sandboxed run of this snippet in the build pipeline.

invoice.paid
invoice.paid (signed sha256=9f2c)

How it works

TypedDict Types Keys With NotRequired comes down to the class WebhookPayload and the function route.

Applying it

Entry signature: def route(payload: WebhookPayload) -> str

route is what another module would consume; nothing else here is load-bearing for callers.

Statements that matter

retry: WebhookPayload = {
    'event': 'invoice.paid',
    'delivery_id': 'd-771',
    'signature': 'sha256=9f2c',
}
target += ' (signed ' + payload['signature'] + ')'
return target
first: WebhookPayload = {
'event': 'invoice.paid',
'delivery_id': 'd-771',
}
def route(payload: WebhookPayload) -> str:
    target = payload['event']
    if 'signature' in payload:
        target += ' (signed ' + payload['signature'] + ')'
    return target

Interactive Tools for This Topic

FAQ

What has to be installed first?
Nothing — the runtime itself provides everything the code touches. Every import resolves inside the standard library — `typing`. The file defines `route` at load time.