Dynamic typing
In Python, types belong to objects rather than to names, and every type check happens while the program runs. Nothing stops you from passing the wrong kind of value; you find out when an operation is attempted on it.
Detailed Explanation
In a statically typed language you tell the compiler what each variable holds. int count = 0; means the name count will hold integers forever, and the compiler refuses to build the program if you break that promise. The check happens before your code ever runs.
Python moves the type information onto the value. A name is a label with no type of its own. The integer 0 knows it is an integer; count knows nothing. When the interpreter reaches count + 1, it looks at whatever object count currently points to, asks that object's type how to add, and either gets an answer or raises TypeError. Do this for every operation and you have dynamic typing.
Distinguish two axes that get mixed up constantly, because interviewers ask about it. Dynamic versus static is about when types are checked: runtime or compile time. Strong versus weak is about how much implicit conversion happens. Python is dynamically typed and strongly typed. "3" + 4 is an error, not "34" and not 7. JavaScript is dynamically and weakly typed, which is why "3" + 4 there produces "34". Python's willingness to fail loudly is a feature, not an inconsistency.
What does dynamic typing buy? Code that works on anything with the right behaviour, without writing an interface or a generic signature. A total(values) function that calls sum works on lists, tuples, generators, and NumPy arrays. Tests get easier, since a fake object with two methods can stand in for a database client. Prototyping gets faster, because you can restructure data mid-thought without updating declarations.
What does it cost? Three things, in rough order of how much they hurt.
- Errors arrive late. A
Nonereturned from a cache lookup travels through four functions before something calls.strip()on it, and the traceback points at the innocent last step. Static types catch this shape of bug before you run anything. - Refactoring is riskier. Renaming a method has no compiler to tell you which of 200 call sites you missed. Your test suite is the only safety net you have.
- It is slower. The interpreter cannot precompute that
price * qtyis integer multiplication, so each operation involves a type lookup and a dispatch. Values are heap-allocated objects rather than raw machine words, which costs memory too.
Since PEP 484, Python has gradual typing as an answer. You annotate what you care about, and an external checker such as mypy or pyright verifies it. Annotations are stored on __annotations__ and otherwise ignored at runtime, so a function annotated -> str can return a list and CPython will not object. That surprises people who expect enforcement. If you want runtime validation, use a library built for it, such as Pydantic or attrs, which read annotations and check values at the boundary.
The practical stance for production code: annotate public functions and data models, run a type checker in CI, and validate data at the edges where it enters your system. Trust the dynamic behaviour in the middle where it earns its keep.
Code Examples
# The name has no type. The object has one, and the object decides.
payload = 42
print(type(payload)) # <class 'int'>
payload = {"user": "ana"} # legal: rebinding, not reassigning a typed slot
print(type(payload)) # <class 'dict'>
# Dynamic does not mean permissive. Python refuses to guess.
try:
print("3" + 4)
except TypeError as exc:
print("TypeError:", exc) # can only concatenate str (not "int") to str
# The fix must be explicit, and you choose which meaning you wanted.
print("3" + str(4)) # 34
print(int("3") + 4) # 7# Annotations document intent; CPython does not enforce them.
def format_username(raw: str) -> str:
return raw.strip().lower()
print(format_username.__annotations__) # {'raw': <class 'str'>, 'return': <class 'str'>}
# This call is a type error that a checker would reject, and Python accepts
# right up to the moment .strip() is attempted on a list.
try:
format_username(["ana"])
except AttributeError as exc:
print(type(exc).__name__) # AttributeError
# The late-failure pattern: a None slips through and blames the wrong line.
def lookup_session(cache, key):
return cache.get(key) # returns None on a miss, silently
session = lookup_session({}, "abc123")
try:
print(session["user_id"]) # fails HERE, but the bug is above
except TypeError as exc:
print(type(exc).__name__) # TypeErrorCommon Gotchas
Type hints are not runtime checks
`def charge(amount: int)` happily receives the string `"10"` and fails later on arithmetic. Run mypy or pyright in CI, and validate untrusted input explicitly at the boundary.
`bool` is a subclass of `int`
`isinstance(True, int)` is `True`, and `True + True` is `2`. Guards written as `isinstance(value, int)` accept booleans, which matters when a config flag reaches code expecting a count.
Prefer capability checks over type checks
`isinstance(value, list)` rejects tuples, generators, and anything list-like a caller passes. Check for the behaviour you need, or accept `collections.abc.Iterable`, and let duck typing do its job.
Dynamic typing shifts work onto your tests
with no compiler verifying call sites, coverage of the unhappy paths is what keeps a Python codebase refactorable. Treat the test suite as the type checker you chose not to have.