Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Python type hints: annotations do not enforce runtime arguments

Last updated: 30 Sept 20264 min read
tutorial
BeginnerBy AITrove Editorial

A Python type annotation describes an intended type contract for tooling; it does not validate an argument when a function is called.

Download Python source kit

Operation contract

The unchecked identity function is annotated with integers but returns a supplied string without runtime rejection. The checked function accepts positive exact integers and rejects the same string. These are separate operations: static analysis can find some mistakes before execution, while runtime boundary checks inspect the actual values arriving from a wire or command line.

Failure and ownership boundary

Python code must define whether a numeric contract includes bool, since bool is an int subclass. An annotation does not settle that domain choice. A cast from typing would change the type checker’s view, not convert or validate data. Python functions: define units, validate input and return a result and Python input exercise: accept an explicit integer grammar show where runtime checks belong. No static type checker is installed or invoked by this source.

Working program

python
def declared_identifier(identifier: int) -> int:
    return identifier

def checked_identifier(identifier: int) -> int:
    if type(identifier) is not int or identifier <= 0:
        raise ValueError("positive integer identifier required")
    return identifier

print(declared_identifier("receipt-41"))
print(checked_identifier(41))
try:
    checked_identifier("receipt-41")
except ValueError:
    print("runtime value rejected")

Output

Output
receipt-41
41
runtime value rejected

Costs and limits

The boundary has fixed-size type and sign checks for these small integers. An annotation adds no automatic parse step, and recursive validation of a large object would carry separate input-size cost.

Common Mistakes

  • An annotation is not automatic input coercion or rejection.
  • Do not use a type cast to claim an untrusted value was checked.

Connected lessons

Python functions: define units, validate input and return a result, Python input exercise: accept an explicit integer grammar, Python dataclasses: frozen fields require an immutable value model.

Apply this boundary

Python Protocol: structural intent without runtime validation.

Related Python operation checks

Mypy static checks: annotations do not validate runtime payloads.

Check the next state boundary

Python TypeGuard: a static narrowing claim is not lasting ownership, Python typing reference: annotations, structural checks and runtime validation differ, Python compatibility checks: parse syntax and execute contracts as separate evidence.

python
type-hints
Storage details