Topic 26 of 64
Dynamic Typing
Overview
Python is dynamically typed — a variable can hold any type and types are checked at runtime, not compile time. This makes Python fast to write but requires careful validation in production systems.
Syntax
python
x = 42 # int
x = "hello" # now a str — no error
x = [1, 2, 3] # now a list
# Check type at runtime
type(x) # <class 'list'>
isinstance(x, list) # TrueCommon Pitfalls
- Dynamic typing is NOT the same as weak typing — Python is strongly typed (5 + '5' raises TypeError).
- Use type hints (def func(x: int) -> str) for documentation and static analysis with mypy.
- Interview tip: Mention that Python's type system is 'duck typing' — if an object has the right methods, it works regardless of its class.
Real-World Example
Function that behaves differently based on input type
example
python
def double(value):
if isinstance(value, str):
return value * 2 # "hi" → "hihi"
elif isinstance(value, (int, float)):
return value * 2 # 5 → 10
raise TypeError(f"Unsupported type: {type(value)}")
print(double("hi")) # hihi
print(double(5)) # 10