Definition
A type hint, also called a type annotation, is a note in Python §12.23 source code that states the type a variable, a function parameter or a return value is expected to have, as in def read(n: int) -> bytes. A Protocol is a class, from the standard module typing, that describes an interface: the methods and attributes an object must have. Any class that has those members matches the Protocol without naming it. Static type checkers, separate programs that examine code without running it, use both; Python itself checks neither while the program runs.
The idea
Python is dynamically typed: a variable can hold a value of any type, and an operation fails only when it is attempted on a value that does not support it. A function checksum(src) calls src.read(4) and then src.close(). Given an object without close, it fails only at that call, after the data has been read; if the call sits on a rarely used path, the mistake can survive testing. A type hint writes the expectation down where a tool can check every call before the program runs.
There are two ways to say which objects a function accepts. Nominal typing accepts an object when its class is declared to derive from a named class. Structural typing accepts an object when it has the right members, whatever its class is called and whatever it derives from. Python programs have long relied on the structural idea informally, under the name duck typing: if it walks like a duck and quacks like a duck, treat it as a duck. A Protocol writes that informal rule down so that a checker can apply it. Like a job advertisement, it lists the skills required, not the school attended, and it cannot confirm that an applicant can actually do the job.
How it works
PEP 484 (Python Enhancement Proposal 484), adopted for Python 3.5, defined the meaning of type hints and added the module typing; PEP 544 added Protocols in Python 3.8. A parameter’s or variable’s hint follows a colon, as in count: int = 0, and a return type follows ->. Python makes the hints of a function or class available in its __annotations__ attribute and does nothing else with them.
A Protocol is declared and checked in these steps.
Declare the interface. A class that lists
Protocolamong its base classes declares the required members, with...as the body of each method:class Source(Protocol):
def read(self, n: int) -> bytes: ...
def close(self) -> None: ...Use it as a type.
def checksum(src: Source) -> intsays thatchecksumaccepts any object that matchesSource.Check statically. A static type checker, such as mypy or Pyright, reads the source without running it. At every call of
checksum, it works out the type of the argument and tests whether that type has a memberreadand a memberclosewhose parameters and results fit the declared ones. It reports each mismatch as an error with its file and line, before the program has run.Run. Python executes the program as if the hints were absent. A wrong argument fails, if at all, only when an operation on it fails.
Check at run time, only if asked.
isinstance(x, Source)raisesTypeErrorunlessSourcecarries the decorator@runtime_checkable. With that decorator,isinstancereturnsTruewhen every member named inSourceis present onx. It does not look at parameters, results or what the members do.
A program that must reject bad values while it runs checks them itself, or uses a third-party library, such as pydantic or beartype, that checks values against the hints at run time.
Worked example
Two classes meet checksum, which reads 4 bytes, closes the source and returns the sum of the bytes modulo 256, the remainder after division by 256. FileSource has both read(self, n: int) -> bytes and close(self) -> None. Pipe has only read.
checksum(FileSource('data.bin'))passes the checker. If the 4 bytes are01 02 03 04in hexadecimal, the sum is and , so the result is 10.checksum(Pipe())is reported by the checker before the program runs, becausePipehas noclose. Without the checker, Python runs the call:readsucceeds, and thensrc.close()raisesAttributeError.checksum(42)is reported by the checker, because an integer has neither member. Python raisesAttributeErroratsrc.read.
Hints alone change nothing at run time. Given def double(x: int) -> int: return x * 2, the call double('ab') returns 'abab' without any error, because multiplying a string by an integer repeats it. The checker reports the call.
Now mark Source with @runtime_checkable and define a class Fake whose body is read = 1 and close = 2. isinstance(Fake(), Source) returns True, because both names are present, although neither is a method: Fake().close() fails with TypeError. A static checker rejects checksum(Fake()).
Stated precisely
Structural match. A class matches a Protocol when, for every member that declares, has a member named of a compatible type. For a method, compatible means that ’s version accepts every argument that ’s version accepts and returns only results that ’s version may return. need not inherit from .
Static guarantee. If a checker reports no error, it has found no violation of its type rules in the code it analyzed; in particular, every argument passed where is expected matches . This depends on four assumptions, which real programs often break.
No value involved has the type
Any, which checkers treat as compatible with every type in both directions.No
castcall or# type: ignorecomment overrides the checker.Every function involved has hints and is checked; by default, mypy skips the inside of a function that has no hints.
Code in other languages, such as C extension modules, behaves as its declared hints say.
Python type checkers are not proven sound, so even a clean result is strong evidence, not proof.
Run-time behavior. Without extra code, the only checks while the program runs are those that the operations make themselves: a missing attribute raises AttributeError, and an unsupported operation raises TypeError. A hint never causes a check. isinstance with a @runtime_checkable Protocol tests only that the member names are present.
Limits and common mistakes
A hint does not validate data that comes from outside the program. json.loads, which parses JSON §12.26 (JavaScript Object Notation) text, returns dictionaries, lists, strings, numbers, booleans and None. Its declared result type is Any, so a checker accepts cfg: Config = json.loads(text) without complaint, although cfg is then a dictionary, not a Config. cast(Config, ...) likewise tells the checker to believe a type without checking anything. Input from an untrusted source needs explicit validation at the trust boundary §1.3, the point where it enters the program.
Types describe shape, not behavior. Source cannot say that read(n) returns at most n bytes, or that close may safely be called twice. Such rules need documentation, tests and run-time checks.
A clean result describes one checker with one configuration. mypy and Pyright disagree in some cases, and options such as a strict mode change what each reports.
Questions answered
Which checks run statically and which are enforced at runtime?
Type hints and Protocols are checked only statically, by a separate type checker such as mypy or Pyright before the program runs; at run time Python enforces none of them, except that isinstance can test an object against a Protocol marked @runtime_checkable. The checker reports calls whose arguments do not fit the declared parameter types, results that do not fit the declared return type, and objects that lack a member a Protocol requires or have it in an incompatible form.
At run time, the only checks are those every operation makes anyway, such as AttributeError when a missing method is called, plus any checks the program contains itself. isinstance against a Protocol works only if the Protocol is marked @runtime_checkable, and even then it checks only that the member names exist, not their signatures, results or behavior. Data from outside the program, such as parsed JSON (JavaScript Object Notation), therefore needs explicit validation code, or a library that checks values against the hints while the program runs.
Related entries: Python (§12.23), Dataclass (§12.45), Assurance case (§10.41), Assumption versus guarantee (§1.36), Static analysis (§3.1). Further reading: [129].