Separate Static Type Tests from Runtime Tests
Core idea
A static checker analyzes declared contracts without running ordinary program logic. A runtime test observes actual values and exceptions. Use positive type assertions such as typing.assert_type and separately tracked negative fixtures for expected diagnostics. In Python 3.13 assert_type returns its argument unchanged; it does not enforce a type.
from typing import assert_typedef label(n: int) -> str: return f'ID-{n}'result = assert_type(label(3), str)print(result, isinstance(result, str))The expected static type is str; the runtime isinstance check is a separate observation. No checker was run on this snippet.
Expected output:
ID-3 TrueDemonstrate a deliberate mismatch
from typing import assert_typevalue = assert_type(5, str) # intentionally invalid static assertionprint(type(value).__name__, value)A type checker should report the mismatch; ordinary execution still returns the integer.
Expected output:
int 5Common mistake
Do not treat a successful runtime run of assert_type as a passing static test. Pin checker versions and configuration; assert expected diagnostic categories for deliberate negative fixtures rather than ignoring all diagnostics.
Practice
Save the positive and negative snippets in separate files; with a Python 3.13-compatible mypy installed, run python -m mypy --show-error-codes on each. Record version, exit status and diagnostic category; keep the intentionally failing file outside the ordinary pass-only suite. No checker run is locally verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Type checking tests
Check your understanding of type checking tests.
What is printed?
from typing import assert_typeprint(assert_type(2,str))What is printed?
def f(x:int)->int:return xprint(isinstance(f("a"),str))What evidence establishes a static assertion passed?
Where should deliberately failing static fixtures live?