What does dynamic typing mean in Python, and how does duck typing relate to it?
Answer
Dynamic typing means a variable is just a name bound to an object, and the type lives on the object, not the name, so the same name can be rebound to values of different types at runtime. Duck typing follows from this: code that calls .read() on an argument works with any object that implements .read(), regardless of its class, because Python checks capability through attribute and method lookup rather than declared type.
Strong answer includes
- type belongs to the object, not the name
- rebinding a name to a different type
- capability over declared type
Practical example
A function that calls
item.upper()works on a str, and would also work on any custom object that defines an
upper()method — no shared base class is required.