Protocols, Literal and Final
suggest changePython 3.8 added three tools to the typing module that make type hints say a lot more than "this is an int":
Protocol(PEP 544) describes an interface by its methods and attributes. Any class with matching members satisfies it, without inheriting from it. This is static duck typing.Literal(PEP 586) limits a value to a fixed set, such asLiteral["r", "w", "a"].Finaland@final(PEP 591) mark names that must not be reassigned, methods that must not be overridden and classes that must not be subclassed.
Python 3.11 built on them with Never and assert_never() for exhaustiveness checks, and LiteralString (PEP 675) for APIs that must only receive strings written in the source code.
All three are hints for type checkers. At runtime Python ignores them, with one exception: protocols marked @runtime_checkable work with isinstance().
Examples were run with Python 3.13.15. Type checker output is from mypy 2.4.0 and pyright 1.1.414. The examples use the type statement and the [T] syntax from Generics with type parameter syntax (PEP 695), and X | Y unions from Modern union and Optional syntax: X | Y.
Protocol: structural typing
Python code has always used duck typing. A function that calls .close() works with anything that has a close method. Before protocols, the only way to type such a function was to pick a base class and make every argument inherit from it. A Protocol describes the shape you need instead:
from typing import Protocol
class SupportsClose(Protocol):
def close(self) -> None: ...
class File:
def close(self) -> None:
print("file closed")
class Socket:
def close(self) -> None:
print("socket closed")
class Robot:
def shutdown(self) -> None:
print("robot off")
def close_all(things: list[SupportsClose]) -> None:
for t in things:
t.close()
close_all([File(), Socket()])
close_all([File(), Robot()])
File and Socket don't mention SupportsClose, but both have a close() method with the right signature, so they are SupportsClose. The method body in the protocol is just ..., because a protocol only declares members.
Python doesn't check the protocol at runtime. The second call fails only when the loop reaches the Robot:
file closed
socket closed
file closed
Traceback (most recent call last):
File "p1.py", line 23, in <module>
close_all([File(), Robot()])
~~~~~~~~~^^^^^^^^^^^^^^^^^^^
File "p1.py", line 20, in close_all
t.close()
^^^^^^^
AttributeError: 'Robot' object has no attribute 'close'
A type checker reports the bug before you run anything:
$ mypy p1.py
p1.py:23: error: List item 1 has incompatible type "Robot"; expected "SupportsClose" [list-item]
Found 1 error in 1 file (checked 1 source file)
The standard library and typeshed are full of protocols like this. collections.abc.Iterable, Sized, Hashable and friends are treated as protocols by type checkers, so any class with __iter__ is an Iterable and any class with __len__ is Sized. Write your own protocol when no existing one fits. A protocol with one or two methods is common, and it makes functions easy to test, because a fake only needs those methods (see Dependency Injection).
Signatures must match
A matching method name is not enough. Parameter and return types have to be compatible too:
from typing import Protocol
class Writer(Protocol):
def write(self, data: str) -> int: ...
class BytesSink:
def write(self, data: bytes) -> int:
return len(data)
class Console:
def write(self, data: str, end: str = "\n") -> int:
print(data, end=end)
return len(data)
def log(w: Writer, msg: str) -> None:
w.write(msg)
log(Console(), "ok")
log(BytesSink(), "boom")
$ mypy p3.py
p3.py:19: error: Argument 1 to "log" has incompatible type "BytesSink"; expected "Writer" [arg-type]
p3.py:19: note: Following member(s) of "BytesSink" have conflicts:
p3.py:19: note: Expected:
p3.py:19: note: def write(self, data: str) -> int
p3.py:19: note: Got:
p3.py:19: note: def write(self, data: bytes) -> int
Found 1 error in 1 file (checked 1 source file)
Console.write has an extra parameter, but it has a default value, so it can still be called as write(data). That makes it compatible.
Attributes and properties
Protocols can require attributes as well as methods. A bare annotation name: str means "a readable and writable attribute of type str". To require only read access, declare a property:
from typing import Protocol
class Named(Protocol):
name: str
class HasArea(Protocol):
@property
def area(self) -> float: ...
class User:
def __init__(self, name: str) -> None:
self.name = name
class Square:
def __init__(self, side: float) -> None:
self.side = side
@property
def area(self) -> float:
return self.side ** 2
class Circle:
def __init__(self, r: float) -> None:
self.r = r
self.area = 3.14159 * r * r # a plain attribute satisfies a read-only property
def greet(x: Named) -> str:
return f"hello {x.name}"
def total_area(shapes: list[HasArea]) -> float:
return sum(s.area for s in shapes)
print(greet(User("ann")))
print(total_area([Square(2), Circle(1)]))
print(greet(Square(3)))
hello ann
7.14159
Traceback (most recent call last):
File "p2.py", line 35, in <module>
print(greet(Square(3)))
~~~~~^^^^^^^^^^^
File "p2.py", line 28, in greet
return f"hello {x.name}"
^^^^^^
AttributeError: 'Square' object has no attribute 'name'
$ mypy p2.py
p2.py:35: error: Argument 1 to "greet" has incompatible type "Square"; expected "Named" [arg-type]
Found 1 error in 1 file (checked 1 source file)
The reverse doesn't work: a read-only property can't satisfy a protocol attribute declared as name: str, because the protocol promises that callers can assign to it.
Generic protocols
Protocols can have type parameters. With the Python 3.12 syntax you write class Source[T](Protocol), and the type checker infers T from the class that is passed in:
from typing import Protocol
class Source[T](Protocol):
def read(self) -> T: ...
class Counter:
def __init__(self) -> None:
self.n = 0
def read(self) -> int:
self.n += 1
return self.n
class Greeting:
def read(self) -> str:
return "hello"
def read_twice[T](src: Source[T]) -> list[T]:
return [src.read(), src.read()]
print(read_twice(Counter()))
print(read_twice(Greeting()))
reveal_type(read_twice(Counter()))
$ mypy p5.py
p5.py:23: note: Revealed type is "list[int]"
Success: no issues found in 1 source file
At runtime (without the reveal_type line, which only type checkers understand unless you import it from typing):
[1, 2]
['hello', 'hello']
A protocol is also a good bound for a type parameter. This biggest() accepts a list of anything that supports <: ints, strings, or your own classes:
from typing import Protocol, Self
class Comparable(Protocol):
def __lt__(self, other: Self, /) -> bool: ...
def biggest[T: Comparable](items: list[T]) -> T:
best = items[0]
for x in items[1:]:
if best < x:
best = x
return best
class Version:
def __init__(self, *parts: int) -> None:
self.parts = parts
def __lt__(self, other: "Version") -> bool:
return self.parts < other.parts
def __repr__(self) -> str:
return "v" + ".".join(map(str, self.parts))
print(biggest([3, 7, 2]))
print(biggest(["pear", "apple"]))
print(biggest([Version(3, 12), Version(3, 14), Version(3, 9)]))
7
pear
v3.14
Adding biggest([object(), object()]) gives:
$ mypy p4.py
p4.py:26: error: Value of type variable "T" of "biggest" cannot be "object" [type-var]
Found 1 error in 1 file (checked 1 source file)
Callback protocols
Callable[[int, Exception], float] can't express keyword-only parameters, default values or overloads. A protocol with a __call__ method can describe any signature:
from typing import Protocol
class Retry(Protocol):
def __call__(self, attempt: int, *, error: Exception) -> float: ...
def exponential(attempt: int, *, error: Exception) -> float:
return 0.1 * 2 ** attempt
def wrong(attempt: int, err: Exception) -> float:
return 1.0
def run(policy: Retry) -> None:
for attempt in range(3):
print(f"attempt {attempt}: wait {policy(attempt, error=TimeoutError()):.1f}s")
run(exponential)
run(lambda attempt, *, error: 0.5)
run(wrong)
attempt 0: wait 0.1s
attempt 1: wait 0.2s
attempt 2: wait 0.4s
attempt 0: wait 0.5s
attempt 1: wait 0.5s
attempt 2: wait 0.5s
Traceback (most recent call last):
File "p6.py", line 18, in <module>
run(wrong)
~~~^^^^^^^
File "p6.py", line 14, in run
print(f"attempt {attempt}: wait {policy(attempt, error=TimeoutError()):.1f}s")
~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: wrong() got an unexpected keyword argument 'error'
$ mypy p6.py
p6.py:18: error: Argument 1 to "run" has incompatible type "Callable[[int, Exception], float]"; expected "Retry" [arg-type]
p6.py:18: note: "Retry.__call__" has type "def __call__(self, attempt: int, *, error: Exception) -> float"
Found 1 error in 1 file (checked 1 source file)
Plain functions, lambdas and objects with a matching __call__ all satisfy Retry.
Inheriting from a protocol explicitly
You can still subclass a protocol. The subclass is then an ordinary class (not a protocol) that inherits any methods the protocol implements. The type checker also verifies that the subclass implements everything:
from typing import Protocol
class Shape(Protocol):
def area(self) -> float: ...
def describe(self) -> str:
return f"{type(self).__name__} with area {self.area():.2f}"
class Square(Shape):
def __init__(self, side: float) -> None:
self.side = side
def area(self) -> float:
return self.side ** 2
class Circle: # not a subclass, still a Shape?
def __init__(self, r: float) -> None:
self.r = r
def area(self) -> float:
return 3.14159 * self.r ** 2
print(Square(3).describe())
def show(s: Shape) -> None:
print(s.area())
show(Circle(1))
class Triangle(Shape):
pass
Triangle()
Square with area 9.00
3.14159
$ mypy p7.py
p7.py:28: error: Argument 1 to "show" has incompatible type "Circle"; expected "Shape" [arg-type]
p7.py:28: note: "Circle" is missing following "Shape" protocol member:
p7.py:28: note: describe
p7.py:33: error: Cannot instantiate abstract class "Triangle" with abstract attribute "area" [abstract]
Found 2 errors in 1 file (checked 1 source file)
Two things to notice:
describeis a member of the protocol even though it has a body. A class that doesn't inherit fromShapemust definedescribeitself to match. Keep default implementations out of protocols you want to use structurally, or put them in a separate helper function.- The checker treats protocol methods without a body as abstract, so
Triangle()is an error. At runtime nothing happens: the instance is created, and callingarea()would returnNone.
runtime_checkable and isinstance
A plain protocol can't be used with isinstance(). Decorate it with @runtime_checkable to allow it:
from typing import Protocol, runtime_checkable
@runtime_checkable
class SupportsClose(Protocol):
def close(self) -> None: ...
class Robot:
def shutdown(self) -> None: ...
class Liar:
close = 42 # an attribute named close, not a method
import io
print(isinstance(io.StringIO(), SupportsClose))
print(isinstance(Robot(), SupportsClose))
print(isinstance(Liar(), SupportsClose))
print(issubclass(io.BytesIO, SupportsClose))
def cleanup(obj: object) -> None:
if isinstance(obj, SupportsClose):
obj.close()
print("closed", type(obj).__name__)
else:
print("nothing to close on", type(obj).__name__)
cleanup(io.StringIO())
cleanup(Robot())
True
False
True
True
closed StringIO
nothing to close on Robot
The runtime check only looks at whether the members exist. It doesn't check signatures, types or even whether close is callable, which is why Liar passes. Type checkers narrow obj to SupportsClose inside the if, so obj.close() type checks.
There are two more restrictions, enforced both at runtime and by type checkers:
from typing import Protocol, runtime_checkable
class Closer(Protocol):
def close(self) -> None: ...
@runtime_checkable
class Named(Protocol):
name: str
class User:
def __init__(self, name: str) -> None:
self.name = name
try:
isinstance(User("ann"), Closer)
except TypeError as e:
print("TypeError:", e)
print(isinstance(User("ann"), Named))
try:
issubclass(User, Named)
except TypeError as e:
print("TypeError:", e)
TypeError: Instance and class checks can only be used with @runtime_checkable protocols
True
TypeError: Protocols with non-method members don't support issubclass(). Non-method members: 'name'.
issubclass() can't work with a data member like name, because an instance attribute set in __init__ doesn't exist on the class.
isinstance() against a runtime-checkable protocol is also much slower than against a regular class, because it has to look up every member. Avoid it in hot loops.
Protocol or abstract base class?
Abstract Base Classes are the other way to define an interface. The difference is who has to know about the interface:
Protocol |
abc.ABC |
|
|---|---|---|
| Implementations must inherit | no | yes (or call register()) |
| Checked by | type checkers | Python, when you instantiate the class |
| Missing method detected | at type check time | TypeError on instantiation |
isinstance() |
only with @runtime_checkable, members only |
yes |
| Works with third-party classes you can't edit | yes | only through register() |
Use a protocol when the callers decide what they need ("anything with read()"), especially for classes you don't own. Use an ABC when you own the hierarchy and want Python itself to refuse incomplete subclasses.
Literal: a closed set of values
Literal[...] is the type of specific values. A parameter annotated with Literal["left", "center", "right"] accepts only those three strings:
from typing import Literal
type Align = Literal["left", "center", "right"]
def pad(text: str, width: int, align: Align = "left") -> str:
if align == "left":
return text.ljust(width)
if align == "right":
return text.rjust(width)
return text.center(width)
print(f"[{pad('hi', 6)}]")
print(f"[{pad('hi', 6, 'right')}]")
print(f"[{pad('hi', 6, 'centre')}]")
choice = "right"
print(f"[{pad('hi', 6, choice)}]")
user_input = " right ".strip()
print(f"[{pad('hi', 6, user_input)}]")
At runtime the typo goes unnoticed: 'centre' falls through to the last branch and centers the text anyway.
[hi ]
[ hi]
[ hi ]
[ hi]
[ hi]
$ mypy l1.py
l1.py:14: error: Argument 3 to "pad" has incompatible type "Literal['centre']"; expected "Literal['left', 'center', 'right']" [arg-type]
l1.py:17: error: Argument 3 to "pad" has incompatible type "str"; expected "Literal['left', 'center', 'right']" [arg-type]
l1.py:20: error: Argument 3 to "pad" has incompatible type "str"; expected "Literal['left', 'center', 'right']" [arg-type]
Found 3 errors in 1 file (checked 1 source file)
Line 17 is the surprising one. mypy infers the type of choice = "right" as str, because the variable could be reassigned to any string later. pyright remembers the literal value and accepts line 17, but both report line 20, where the value comes from a computation. To keep a literal type, annotate the variable (choice: Align = "right") or mark it Final (see below).
A literal can be a string, bytes, int, bool, enum member or None. Literal[None] is the same as None. Floats and arbitrary expressions are not allowed. Several Literals in a union merge into one, and duplicates are removed:
from typing import Literal
print(Literal[1, 2] | Literal[3])
print(Literal["a", "a", "b"])
typing.Union[typing.Literal[1, 2], typing.Literal[3]]
typing.Literal['a', 'b']
Type checkers treat the first line as Literal[1, 2, 3].
Literal with overloads
A classic use of Literal is a flag that changes the return type. open() in typeshed returns TextIOWrapper for "r" and BufferedReader for "rb" this way. Combine Literal with @overload:
from typing import Literal, overload
@overload
def fetch(url: str, as_text: Literal[True]) -> str: ...
@overload
def fetch(url: str, as_text: Literal[False]) -> bytes: ...
def fetch(url: str, as_text: bool) -> str | bytes:
data = b"<html></html>"
return data.decode() if as_text else data
reveal_type(fetch("x", True))
reveal_type(fetch("x", False))
$ mypy l2.py
l2.py:11: note: Revealed type is "str"
l2.py:12: note: Revealed type is "bytes"
Success: no issues found in 1 source file
Callers get a precise type instead of str | bytes and don't need an isinstance check.
Validating untrusted strings
Values from users, files or the network are plain str. To turn one into a Literal type, check it against the allowed values. typing.get_args() gives you the values at runtime, so the list is written only once. A match statement with literal patterns narrows the type in both mypy and pyright:
from typing import Final, Literal, get_args
Level = Literal["debug", "info", "warning", "error"]
LEVELS: Final = get_args(Level)
def parse_level(s: str) -> Level:
match s.lower():
case "debug" | "info" | "warning" | "error" as level:
return level
case other:
raise ValueError(f"unknown level {other!r}, expected one of {LEVELS}")
print(LEVELS)
print(parse_level("INFO"))
try:
parse_level("verbose")
except ValueError as e:
print(e)
('debug', 'info', 'warning', 'error')
info
unknown level 'verbose', expected one of ('debug', 'info', 'warning', 'error')
get_args() works on Level because it was created with a plain assignment. For an alias made with the type statement, use get_args(Level.__value__).
An if s == "debug" or s == "info" ... chain works in pyright but not in mypy, which doesn't narrow a str to a literal with ==. if s in LEVELS: return cast(Level, s) works everywhere, at the cost of a cast.
Literal or Enum?
Literal["pending", "paid"] and an Enum both describe a closed set. Literal is lighter: callers pass ordinary strings, and values convert to and from JSON without any code. An Enum gives you a real runtime type with iteration, methods and isinstance checks. A Literal of enum members, such as Literal[Color.RED, Color.GREEN], picks a subset of an enum.
Exhaustiveness checks with Never and assert_never
Never (Python 3.11, previously spelled NoReturn) is the type with no values. No variable can ever hold a Never. Type checkers use this to verify that you handled every case: after all the possibilities have been narrowed away, the remaining type is Never. If a possibility is left, typing.assert_never() reports it:
from typing import Literal, assert_never
type Status = Literal["pending", "paid", "shipped", "refunded"]
def label(status: Status) -> str:
if status == "pending":
return "Waiting for payment"
elif status == "paid":
return "Payment received"
elif status == "shipped":
return "On its way"
else:
assert_never(status)
print(label("paid"))
Payment received
$ mypy n1.py
n1.py:13: error: Argument 1 to "assert_never" has incompatible type "Literal['refunded']"; expected "Never" [arg-type]
Found 1 error in 1 file (checked 1 source file)
The checker tells you which value is missing. Add a branch for "refunded" and the error disappears. This turns "I added a new status, now find every place that handles statuses" into a list of type errors. At runtime assert_never() raises AssertionError if it's ever reached. The same works with enums, unions of classes and match statements, as shown in Assertions.
Never is also the return type of a function that never returns normally, because it always raises or exits:
from typing import Never, NoReturn
def fail(msg: str) -> Never:
raise SystemExit(f"fatal: {msg}")
def port_from(s: str) -> int:
if s.isdigit():
return int(s)
fail(f"bad port {s!r}")
print(port_from("8080"))
print(Never, NoReturn)
8080
typing.Never typing.NoReturn
port_from has no return after fail(...), but type checkers don't complain about a missing return, because they know fail() doesn't come back. Never and NoReturn mean the same thing; Never reads better in parameter positions like assert_never(arg: Never).
LiteralString: only strings from the source code
SQL injection happens when user input is formatted into a query string. Python 3.11 added LiteralString, a type that accepts only strings built from literals in your code. Literals, and strings combined from literals with +, join or f-strings of literals, are LiteralString. Anything derived from input(), a file or a request is plain str:
import sqlite3
from typing import LiteralString
def query(db: sqlite3.Connection, sql: LiteralString, *params: object) -> list[tuple]:
return db.execute(sql, params).fetchall()
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE users (name TEXT, role TEXT)")
db.executemany("INSERT INTO users VALUES (?, ?)", [("ann", "admin"), ("bob", "user")])
TABLE = "users"
role = input("role? ")
print(query(db, "SELECT name FROM users WHERE role = ?", role))
print(query(db, "SELECT count(*) FROM " + TABLE))
print(query(db, f"SELECT name FROM users WHERE role = '{role}'"))
role? admin
[('ann',)]
[(2,)]
[('ann',)]
The third query is the dangerous one: a role of ' OR '1'='1 would return every user. pyright catches it:
$ pyright s1.py
s1.py:16:17 - error: Argument of type "str" cannot be assigned to parameter "sql" of type "LiteralString" in function "query"
"str" is not assignable to "LiteralString" (reportArgumentType)
1 error, 0 warnings, 0 informations
The first two queries are accepted: the first passes user data as a parameter, and the second is built only from literals. mypy 2.4 doesn't implement PEP 675 yet and treats LiteralString as str, so it reports nothing. The protection is only as good as your checker.
Final: names that must not change
Python has no constants. Final tells the type checker that a name is assigned once and never again:
from typing import Final
MAX_RETRIES: Final = 3
API_URL: Final[str] = "https://api.example.com"
class Config:
TIMEOUT: Final = 30.0
def __init__(self, name: str) -> None:
self.name: Final = name
MAX_RETRIES = 5
MAX_RETRIES += 1
Config.TIMEOUT = 60
cfg = Config("prod")
cfg.name = "dev"
class Child(Config):
TIMEOUT = 10.0
print(MAX_RETRIES, Config.TIMEOUT, cfg.name, Child.TIMEOUT)
Python happily runs it:
6 60 dev 10.0
Every reassignment is a type error, including redefining the attribute in a subclass:
$ mypy f1.py
f1.py:12: error: Cannot assign to final name "MAX_RETRIES" [misc]
f1.py:13: error: Cannot assign to final name "MAX_RETRIES" [misc]
f1.py:14: error: Cannot assign to final attribute "TIMEOUT" [misc]
f1.py:17: error: Cannot assign to final attribute "name" [misc]
f1.py:20: error: Cannot assign to final name "TIMEOUT" [misc]
Found 5 errors in 1 file (checked 1 source file)
Rules for Final:
- Write
Finalalone to let the checker infer the type, orFinal[str]to state it. - A final attribute is assigned either in the class body or in
__init__, not both. Finalprotects the name, not the object.ITEMS: Final = [1, 2]can't be rebound, butITEMS.append(3)is allowed. Use a tuple orfrozenset(orSequence[int]as the type) for read-only data.- In a dataclass,
x: Final[int]is still a normal__init__field, but the checker won't let you reassign it after construction.
Final keeps literal types
Because a Final name can't change, the checker gives it the literal type of its value. This is how you write a constant that can be passed where a Literal is expected:
from typing import Final, Literal
type Align = Literal["left", "center", "right"]
def pad(text: str, width: int, align: Align) -> str:
return text.center(width) if align == "center" else text.ljust(width)
DEFAULT: Final = "center"
fallback = "center"
print(f"[{pad('hi', 6, DEFAULT)}]")
print(f"[{pad('hi', 6, fallback)}]")
$ mypy f3.py
f3.py:12: error: Argument 3 to "pad" has incompatible type "str"; expected "Literal['left', 'center', 'right']" [arg-type]
Found 1 error in 1 file (checked 1 source file)
DEFAULT is Literal['center'] and is accepted; fallback is str and isn't.
@final methods and classes
The @final decorator (lowercase, also in typing) works on methods and classes. A final method can't be overridden, and a final class can't be subclassed:
from typing import final
class Base:
@final
def checksum(self) -> int:
return 42
def name(self) -> str:
return "base"
@final
class Token:
def __init__(self, value: str) -> None:
self.value = value
class Sub(Base):
def checksum(self) -> int:
return 0
class SpecialToken(Token):
pass
print(Sub().checksum(), SpecialToken("x").value)
print(getattr(Base.checksum, "__final__"), getattr(Token, "__final__"))
0 x
True True
$ mypy f2.py
f2.py:17: error: Cannot override final attribute "checksum" (previously declared in base class "Base") [misc]
f2.py:20: error: Cannot inherit from final class "Token" [misc]
Found 2 errors in 1 file (checked 1 source file)
Again Python doesn't stop you. Since Python 3.11, @final sets __final__ = True on the decorated object, so frameworks and tests can detect it at runtime.
Use @final on classes that aren't designed for extension, such as value objects. That leaves you free to change their internals later. Use it on methods that subclasses must not change, such as a template method that calls overridable hooks. The opposite tool, marking a method that is meant to override a base method, is @typing.override (Python 3.12).
Older Python versions
Everything in this article except Never, assert_never and LiteralString is available in typing since Python 3.8. For older versions, or to use newer features on older Pythons, import the same names from the typing_extensions package. It's what type checkers recommend, and it costs nothing at runtime once the standard library catches up.
Summary
| Tool | Since | Use it for |
|---|---|---|
Protocol |
3.8 | interfaces matched by shape, without inheritance |
@runtime_checkable |
3.8 | isinstance() against a protocol (checks member names only) |
Literal[...] |
3.8 | a parameter or value limited to a fixed set |
Final |
3.8 | constants and attributes assigned exactly once |
@final |
3.8 | methods that can't be overridden, classes that can't be subclassed |
Never, assert_never() |
3.11 | functions that never return, exhaustiveness checks |
LiteralString |
3.11 | APIs such as SQL that must only get strings from source code |
Things to remember:
- None of these change what Python does at runtime. Run mypy or pyright to get the benefit.
- A protocol member with a default body is still a member. Structural implementations must define it too.
isinstance()with a runtime-checkable protocol only checks that the names exist.- mypy infers
x = "left"asstr. Use an annotation orFinalto keep the literal type. - End every
if/elifchain ormatchover aLiteral, enum or union withassert_never()so new cases can't be forgotten.