Python uses dynamic, strong typing with pass-by-object-reference (call-by-sharing): function parameters have no static type constraints at compile time, so any object can be passed into any parameter slot, type compatibility is verified at runtime when operations/attributes are accessed on the object (duck typing), and optional type hints (def fn(x: int) -> str:) serve solely as metadata for static type checkers (mypy, pyright) and IDEs without enforcing runtime checks unless explicitly validated with isinstance() or a runtime validator like Pydantic.
Basic Example
# 1. No type annotations: Any object supporting `+` works via runtime duck typing
def combine(a, b):
return a + b
print(combine(10, 25)) # 35 (int + int)
print(combine("py", "thon")) # 'python' (str + str)
print(combine([1, 2], [3])) # [1, 2, 3] (list + list)
# 2. Optional type hints (checked by mypy/pyright/IDEs, NOT enforced by Python at runtime):
def repeat_label(label: str, count: int = 2) -> str:
return label * count
print(repeat_label("ok-", 3)) # 'ok-ok-ok-'
print(repeat_label([1], 2)) # [1, 1] -> Runs at runtime despite `str` annotation!
# 3. Explicit runtime enforcement when strict parameter types are required:
def strict_repeat(label: str, count: int) -> str:
if not isinstance(label, str) or isinstance(count, bool) or not isinstance(count, int):
raise TypeError("Expected (str, int)")
return label * count
Key Details & Edge Cases
- Dynamic typing $\neq$ weak typing (Python is strongly typed):
- Unlike JavaScript or PHP, Python never silently coerces incompatible types at runtime (
combine("age: ", 25)raisesTypeError: can only concatenate str (not "int") to strinstead of producing"age: 25"). Objects carry their concrete type tag on the heap, while variable/parameter names are untyped bindings pointing to those objects.
- Unlike JavaScript or PHP, Python never silently coerces incompatible types at runtime (
- Pass-by-object-reference (mutating vs. rebinding a parameter):
- Passing an argument binds the parameter name to the same object reference in memory:
- Mutating a mutable argument in place (
items.append(4)) updates the caller’s list because both names reference the same object. - Rebinding the parameter name (
items = [9, 9]) only points the local parameter variable to a new object without affecting the caller’s variable.
- Mutating a mutable argument in place (
- Because default parameter values are evaluated once at
defdefinition time, never use mutable objects likedef add_item(x, bucket=[])as defaults—usebucket: list | None = Noneinstead.
- Passing an argument binds the parameter name to the same object reference in memory:
boolis a subclass ofint(isinstance(True, int) == True):- When writing runtime type checks for integer parameters,
isinstance(True, int)returnsTruebecauseboolinherits fromint(True == 1,False == 0). Guard against booleans explicitly viaisinstance(x, int) and not isinstance(x, bool).
- When writing runtime type checks for integer parameters,
- Duck typing & Structural Subtyping (
collections.abc/typing.Protocol):- Idiomatic Python functions accept abstract behaviors rather than concrete classes—for example, annotating
items: Iterable[int]or checkingisinstance(x, collections.abc.Sequence)lets callers pass alist,tuple,range, or generator seamlessly without rewriting the function.
- Idiomatic Python functions accept abstract behaviors rather than concrete classes—for example, annotating
- Automatic runtime type validation (
pydantic.validate_callorbeartype):- When building public APIs, CLI entry points, or data pipelines that need type hints enforced automatically at runtime without manual
isinstance()boilerplate, decorate functions with.validate_call(pip install pydantic) or@beartype.beartype(pip install beartype).
- When building public APIs, CLI entry points, or data pipelines that need type hints enforced automatically at runtime without manual
Comparison of Parameter Typing Approaches in Python
| Approach | Checked Before Running? (IDE / CI) | Enforced at Runtime? | Performance Overhead | Best Used When |
|---|---|---|---|---|
Unannotated Dynamic Parameters (def fn(x):) |
No (treated as Any) |
No (fails with TypeError/AttributeError on invalid op) |
Zero | Quick scripts, REPL exploration, and generic polymorphic helpers. |
Static Type Annotations (def fn(x: int) -> str:) (Recommended) |
Yes (mypy, pyright, VS Code/PyCharm) |
No (stored in fn.__annotations__ only) |
Zero at runtime | Production applications, libraries, and team codebases for IDE autocomplete and CI bug detection. |
Explicit isinstance() / abc Guard Clauses |
Yes (narrows types for static checkers too) | Yes (raises TypeError immediately) |
Negligible (~nanoseconds) | Public library boundaries or overloaded functions branching on argument type (.singledispatch). |
Runtime Validator Decorators (.validate_call / @beartype) |
Yes | Yes (coerces or raises ValidationError / BeartypeCallHintParamViolation) |
Low–Moderate (per-call validation) | API handlers, config loaders, and untrusted external inputs requiring strict runtime guarantees. |
You must log in or register to comment.
