Lesson · Type Hints & Static Typing
Type Aliases, Literals & Final
65 min readType Aliases, Literals & Final
Aliases, `Literal`, `Final`, `ClassVar`, and `NewType` let type annotations express domain intent beyond basic container shapes. Use them when they remove ambiguity rather than simply making annotations longer.
Learning goals
- Give a repeated type expression a domain name with a type alias and say when the name earns its keep.
- Constrain a parameter to an exact set of values with
Literaland predict what a checker rejects. - Mark constants with
Finaland explain why the restriction is checked rather than enforced. - Distinguish class-level attributes from instance fields with
ClassVar. - Create a distinct identifier type with
NewTypeand describe what it is at runtime: a function that returns its argument.
Mental model
Each tool adds one promise to a plain annotation, and none of them changes what the interpreter accepts at runtime. Reach for the tool that removes a real ambiguity and skip the ones that only lengthen the signature.
Mental model
read it top to bottom
tool what it adds to a plain type alias a domain name for a repeated shape Literal the exact values that are allowed Final the promise of a single assignment ClassVar separation between class state and instance fields NewType a distinct identity the checker keeps apart from the base type
Core idea
Beyond naming types, annotations can narrow them: an alias names a repeated shape, Literal lists the exact values allowed, Final promises a single assignment, ClassVar separates class state from instance fields, and NewType gives a value a distinct identity. All of these live in the checker's model, so they catch mix-ups and accidental rebinds before you run anything, while the interpreter keeps executing the same objects it always did. The judgment call is restraint: add a constraint only when it removes ambiguity a reader or a checker would otherwise miss.
Type aliases
A type alias gives a meaningful name to a reusable type expression. It improves readability when the alias communicates domain intent rather than merely shortening syntax.
Literal
Literal["read", "write"] narrows a type to the exact values listed, so a checker accepts only those and rejects every other string. The listed values must be literals such as strings, bytes, integers, or booleans, and at runtime Literal[...] is metadata only: calling with an unlisted value still runs.
Final
Final marks a name as intended for a single assignment: MAX_RETRIES: Final = 3 tells a checker that rebinding it later is an error. The restriction lives in the checker, since Python itself allows the rebind at runtime, and it protects the name rather than the object behind it.
ClassVar
ClassVar[int] on a class attribute says the value belongs to the class rather than to each instance, so tools such as dataclasses leave it out of the instance fields. Assigning it through self is flagged because that would create a shadowing instance attribute.
NewType
NewType("UserId", int) builds a distinct nominal type from an existing one: a checker treats UserId as separate from int, so mixing the two is an error. At runtime the call is a plain function that returns its argument, so UserId(7) is just 7.
Walkthrough
UserId = NewType("UserId", int)creates a distinct check-time type, and the runtime callUserId(7)simply returns7; from here a checker will not let a bareintstand in where aUserIdis expected.Mode = Literal["read", "write"]lists the only strings the parameter accepts, so"delete"is a checker error even though the call would still execute.MAX_RETRIES: Final = 3claims a single assignment, so a checker flags any later rebinding while Python never prevents it, andopen_resource(user_id: UserId, mode: Mode)shows both alias-based types working in a real signature.- Predict before running: what the program prints, whether
open_resource(7, "read")still runs, and whether rebindingMAX_RETRIESraises at runtime.
Experiments to try
- Call
open_resource(7, "read")and thenopen_resource(UserId(7), "write"); run both, then note which one a checker rejects and why the output is identical anyway. - Print
UserId,UserId(7), andtype(UserId(7))and state what the runtime objects are. - Rebind
MAX_RETRIES = 5after the declaration and confirm Python allows it; describe what theFinalannotation did and did not do. - Extend
ModetoLiteral["read", "write", "append"]and update a call; explain how the checker's accepted set follows the literal list.
Common mistakes
- Expecting
Finalto freeze a value: it stops rebinding the name, soITEMS: Final = []can still be mutated withITEMS.append(1)because the list object itself is untouched by the rule. - Expecting
NewTypeorLiteralto validate at runtime: both are check-time constructs, soopen_resource(7, "read")prints its line and only the checker objects. - Using a plain alias where identity matters:
Record = dict[str, str]is interchangeable with its definition, so it cannot catch a swap between two same-shaped types, whileNewTypekeeps the identities apart. - Adding
ClassVaror omitting it without understanding the difference: a field that dataclasses should treat as an instance attribute, or as class state, changes__init__and equality depending on which promise you wrote.
Practice: Easy
- Run the worked example, then rebind
MAX_RETRIESand confirm Python permits it; write one sentence on whatFinalpromised that the interpreter did not enforce. - Pass
"delete"toopen_resource'smodeparameter, confirm the call still runs, and list the two values the checker actually accepts. - Print
UserId(7), its type, andisinstance(UserId(7), int); explain whatNewTypebuilt at runtime.
Practice: Medium
- Define
Scores = dict[str, int]and annotate a function with it; compare that signature with one written asdict[str, int]inline and say which version explains intent. - Define
OrderId = NewType("OrderId", int)besideUserIdand show that passing anOrderIdwhere aUserIdis expected is a checker error even though both are plain ints at runtime. - Write a small class with
limit: ClassVar[int] = 3and an instance attribute set in__init__; then assignself.limit = 5and explain why a checker flags it even though the instance attribute is created at runtime.
Practice: Hard
- Build a small order module with
OrderId = NewType("OrderId", int), aStatus = Literal["new", "paid", "shipped"], aFinaldefault table, and a function taking all three; list what each promise prevents before writing the code. - Failure lab: rebind a
Finalname, mutate the object behind anotherFinalname, and pass"delete"whereLiteral["read", "write"]is expected; explain why each slipped past runtime and which one a checker catches. - Define
Score = floatandPercentage = NewType("Percentage", float)and describe one concrete bug each catches and one it does not, given that both rest on the same base type.
Lesson checklist
- I can write a type alias that names a repeated shape and say when it improves a signature.
- I can restrict a parameter to exact values with
Literaland predict what a checker rejects. - I can explain what
Finaladds at check time and the mutation it does not prevent. - I can use
NewTypeto keep two same-shaped identifiers apart and describe what the runtime call returns.
Remember
Aliases, `Literal`, `Final`, `ClassVar`, and `NewType` all add a promise to a plain annotation: a name for a shape, a closed set of values, a single assignment, class-level storage, or a distinct identity. Every one of those promises lives in the checker's model, so the interpreter runs the same code whether or not the promise is kept. Add them where they remove a real ambiguity, and remember that `Final` stops rebinding a name, not mutating what it points at.
Interview angles
What is the main purpose of **Type aliases**?+
A type alias gives a meaningful name to a reusable type expression. It improves readability when the alias communicates domain intent rather than merely shortening syntax.
What should you pay attention to when using **Literal**?+
Literal["read", "write"] narrows a type to the exact values listed, so the checker accepts only those and rejects anything else. The constraint lives in the checker: at runtime the call still executes with an unlisted value.
How does **Final** fit into this lesson?+
Final marks a name as intended for a single assignment, so a checker flags a later rebinding. Python does not enforce that, so MAX_RETRIES = 5 still runs, and Final says nothing about mutating the object behind the name.
Why does `ITEMS: Final = []` still allow `ITEMS.append(1)`?+
Final restricts rebinding the name, not mutating the object the name refers to. A checker rejects ITEMS = [...], while append changes the list in place and is allowed.