1. What Is Dynamic Typing?
Dynamic Typing means that a variable's type does not need to be explicitly declared when the code is written; instead, its type is determined at runtime by the object the variable references.
For example:
value = 100
value = "Hello Python"
value = [1, 2, 3]
The same variable value can successively reference an integer, a string, and a list object.
In Python, this is legal because Python does not require a variable to be bound to a fixed type when it is declared.
The counterpart to this is statically typed languages such as Java:
int value = 100;
// Compile error: cannot assign a string to an int variable
value = "Hello";
In Java, once a variable is declared with the int type, it generally cannot later be assigned a string.
Python, by contrast, does not require that a variable always reference an object of the same type when it is assigned.
1.1 Core Characteristics of Dynamic Typing
Dynamic typing mainly has the following characteristics:
- Variable types do not need to be declared in advance.
- A variable can reference objects of different types at different times.
- Type information participates in operations and checks at runtime.
- Some type errors are exposed only when the program executes the corresponding code.
- A variable's type and an object's type must be distinguished.
For example:
number = 100
print(type(number))
number = "Python"
print(type(number))
Output:
<class 'int'>
<class 'str'>
Pay special attention: a variable itself does not carry a permanently fixed type. number is a name that successively binds to different objects.
2. Python Is a Dynamically Typed Language, but That Does Not Mean It Has No Types
To understand Python's dynamic typing, you must first distinguish three concepts:
- Variable name (Name)
- Object
- Object type (Type)
In Python, a variable name is not an independent container that stores a value of some fixed type in the traditional sense; it is a name used to reference an object.
For example:
age = 18
This can be understood as:
- Create or obtain an integer object
18. - Bind the name
ageto that object. - The object's type is
int.
When the following is executed:
age = "eighteen"
What happens is:
- A string object is created or obtained.
- The name
ageis rebound to that string object. - The original integer object is no longer accessed through the name
age.
Therefore, dynamic typing does not mean that objects have no type; it means that name binding does not require a fixed type.
2.1 Objects Always Have a Type
In Python, every object has its own type.
a = 10
b = "hello"
c = [1, 2, 3]
print(type(a))
print(type(b))
print(type(c))
Output:
<class 'int'>
<class 'str'>
<class 'list'>
The type determines which operations an object supports and how those operations should be performed.
For example:
number = 10
message = "hello"
print(number + 5)
print(message + " world")
Integers support numeric addition, and strings support string concatenation.
But the following operation will produce an error:
number = 10
message = "hello"
result = number + message
At runtime it will raise:
TypeError: unsupported operand type(s) for +: 'int' and 'str'
This shows that although Python allows dynamic binding, it does not remove the type constraints on objects.
2.2 The Relationship Between Names, Objects, and Types
Python's basic model can be understood as:
flowchart TD
A["Variable name"] --> B["Binding relationship"]
B --> C["Object"]
C --> D["Object type"]
C --> E["Object data"]
D --> F["Determines supported operations"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#FFF5DE,stroke:#E8D29A,color:#334155
style C fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style D fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style E fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style F fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
The most important conclusion here is:
Python's dynamic typing means that a name can be bound to objects of different types during execution, not that the object itself has no type.
3. Differences Between Dynamic Typing and Static Typing
Dynamic typing and static typing are two important design approaches in programming language type systems.
3.1 Static Typing
Static typing usually requires determining the types of expressions during compilation or another pre-execution analysis phase, and checking the program according to type rules.
For example, Java:
int age = 18;
String name = "Alice";
age = "twenty"; // incompatible types
The compiler can detect type mismatch problems before the program runs.
Common statically typed languages include:
- Java
- C
- C++
- Rust
- Go
- C#
The type systems and checking mechanisms of different languages are not exactly the same, but they all have relatively strong pre-execution type analysis capabilities.
3.2 Dynamic Typing
Dynamically typed languages usually determine object types during execution and check whether operations are valid when performing the relevant operations.
For example, Python:
value = 100
value = "Python"
value = [1, 2, 3]
These assignments can all execute normally.
But if an unsupported operation is performed:
value = 100 + "Python"
a TypeError will be raised at runtime.
Common dynamically typed languages include:
- Python
- JavaScript
- Ruby
- PHP
3.3 Core Differences
| Comparison dimension | Dynamic typing | Static typing |
|---|---|---|
| Type determination | Usually determined at runtime | Usually determined during pre-execution analysis |
| Variable type declaration | Usually not mandatory | Depends on the language; usually places more emphasis on type declarations or inference |
| Type checking | Mainly relies on runtime | Usually includes pre-execution checking |
| Type error detection | May be discovered when the relevant execution path is reached | Many type errors can be discovered in advance |
| Development flexibility | Relatively high | Usually has more explicit type constraints |
| Runtime overhead | May require dynamic typing-related processing | Depends on the language and implementation |
| Typical languages | Python, JavaScript | Java, C#, Rust, Go |
It should be noted that dynamic typing and static typing are not equivalent to interpreted and compiled.
For example:
- Python is usually classified as a dynamically typed language, but CPython compiles source code into bytecode.
- Java is a statically typed language and also has a virtual machine and runtime type mechanisms.
- TypeScript performs static type checking during development and is ultimately usually compiled to JavaScript for execution.
Type systems and code execution methods are two different dimensions.
4. Python's Dynamic Typing Mechanism
To understand dynamic typing, it is necessary to further understand Python's name binding, object model, and runtime type information.
4.1 Name Binding Mechanism
Assignment operations in Python are essentially binding names to objects.
value = 100
other = value
value = 200
print(value)
print(other)
Output:
200
100
This is not a case of copying the integer 100 from value into an independent variable container represented by other.
More precisely, value and other are both initially bound to the integer object 100; afterward, value is rebound to the integer object 200.
This can be understood through the following relationship:
flowchart TD
A["Initial State"] --> B["value and other"]
B --> C["integer object 100"]
D["Execute value = 200"] --> E["value rebound"]
E --> F["integer object 200"]
E --> G["other still bound"]
G --> C
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style C fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
style E fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style F fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style G fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
This is also foundational to Python's name binding and object reference model.
4.2 Runtime Type Information
Python objects have type information at runtime, which can be viewed with type().
value = 100
print(type(value))
value = "hello"
print(type(value))
Output:
<class 'int'>
<class 'str'>
type() returns the type object to which the object belongs.
You can also use isinstance() to determine whether an object belongs to a given type or its subclasses.
value = 100
print(isinstance(value, int))
print(isinstance(value, str))
Output:
True
False
These two functions are important tools for runtime type checking in Python.
4.3 Types Determine the Behavior Objects Support
Types in Python are not only used to identify data categories but also determine which operations an object can participate in.
For example:
number = 10
text = "hello"
items = [1, 2, 3]
print(number + 5)
print(text.upper())
print(items.append(4))
Objects of different types support different methods and operations.
You can use dir() to view the attributes and methods accessible on an object:
print(dir("hello"))
print(dir([1, 2, 3]))
However, dir() displays the names of an object's visible attributes and is not equivalent to a complete type specification or all possible runtime behaviors.
5. Python's Type Checking Mechanism
Type checking refers to the process of determining whether an object or expression meets expected type requirements.
Python's type checking can mainly be understood from two perspectives: runtime checking and static type checking.
5.1 Runtime Type Checking
Runtime type checking determines whether an operation is valid based on the object's actual type during program execution.
For example:
def add(a, b):
return a + b
print(add(10, 20))
print(add("Hello", "Python"))
Both calls succeed.
But if incompatible objects are passed:
print(add(10, "Python"))
a TypeError will be raised at runtime.
The reason is that the function definition does not restrict parameter types; the caller decides which objects are actually passed in, and the + operator does not support combining an integer and a string here.
5.2 Using type() to Check Types
type() can obtain the actual type of an object.
value = 100
if type(value) is int:
print("这是整数")
Note that type(value) is int only checks whether the object is exactly of type int; it does not treat subclasses of int as int.
For example:
class MyInt(int):
pass
value = MyInt(100)
print(type(value) is int)
print(isinstance(value, int))
Output:
False
True
Therefore, in ordinary business code, isinstance() is usually preferred.
5.3 Using isinstance() to check types
isinstance() can determine whether an object belongs to a specified type or a subclass of the specified type.
value = 100
if isinstance(value, int):
print("这是一个整数对象")
You can also check multiple types at once:
value = "hello"
if isinstance(value, (str, bytes)):
print("这是字符串或字节序列")
In scenarios where support for inheritance relationships is needed, isinstance() is usually more appropriate than using type() directly.
5.4 Typical scenarios for type checking
For example, write a calculation function that accepts only numbers:
def calculate_discount(price):
if not isinstance(price, (int, float)):
raise TypeError("price 必须是数字")
return price * 0.9
print(calculate_discount(100))
When a string is passed in:
calculate_discount("100")
It will raise a clear TypeError.
This allows parameters to be checked at the function entry point, preventing erroneous data from entering subsequent business logic.
Note that bool is a subclass of int, so:
print(isinstance(True, int))
The result is:
True
If the business logic does not allow Boolean values as numeric input, you can add stricter checks:
def calculate_discount(price):
if isinstance(price, bool) or not isinstance(price, (int, float)):
raise TypeError("price 必须是数字,不能是布尔值")
return price * 0.9
6. Duck Typing: Python's Philosophy of Type Usage
Python's dynamic type system is closely related to duck typing.
The core idea of duck typing is:
If an object has the required behavior, it can be used in the corresponding scenario without necessarily checking which specific type it belongs to.
This idea is usually summarized in one sentence:
"If it walks like a duck and it quacks like a duck, it's a duck."
6.1 Traditional type-checking approach
Suppose there is a function that needs to accept objects that can produce sounds.
One approach is to check the specific type:
class Dog:
def speak(self):
return "Woof"
class Cat:
def speak(self):
return "Meow"
def make_sound(animal):
if isinstance(animal, (Dog, Cat)):
return animal.speak()
raise TypeError("不支持的动物类型")
This approach relies on an explicit list of types.
When new types such as Bird and Duck appear later, the checking logic must be continuously modified.
6.2 The duck typing approach
You can focus directly on whether the object provides the required method:
class Dog:
def speak(self):
return "Woof"
class Cat:
def speak(self):
return "Meow"
class Duck:
def speak(self):
return "Quack"
def make_sound(animal):
return animal.speak()
print(make_sound(Dog()))
print(make_sound(Cat()))
print(make_sound(Duck()))
Output:
Woof
Meow
Quack
The function does not need to know which class the object specifically belongs to; as long as the object supports the speak() method, it can work normally.
6.3 How duck typing works
flowchart TD
A["Call the function"] --> B["Pass in an object"]
B --> C["Call the method required by the object"]
C --> D{"Does the object support this behavior"}
D -->|Supported| E["Normal execution"]
D -->|Not supported| F["Runtime exception"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
style E fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style F fill:#FBE9E9,stroke:#D9AAAA,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
6.4 Advantages of Duck Typing
- Reduces the code's dependence on concrete classes.
- Improves compatibility between different objects.
- Makes it easy to add new implementations.
- Reduces unnecessary type checks.
- Makes it easier to write generic functions and tools.
However, duck typing does not mean that types can be completely ignored.
If an object lacks a required method, the program may still fail at runtime.
Therefore, in large projects, you can combine type annotations, protocols (Protocol), and tests to clearly define the behavioral requirements that an object must satisfy.
7. Strong Typing and Weak Typing in Python
Dynamic typing and strong vs. weak typing are two different concepts.
- Dynamic typing vs. static typing: mainly discusses when types are determined and checked.
- Strong typing vs. weak typing: mainly discusses how strict the rules are for operations and conversions between different types.
Python is generally classified as a dynamic, strongly typed language.
7.1 Python Does Not Arbitrarily Perform Incompatible Type Conversions
For example:
number = 10
text = "20"
result = number + text
This raises:
TypeError
Python will not automatically convert the string "20" to an integer before performing the addition.
7.2 Explicit Type Conversion
If calculation is actually needed, you can explicitly convert the type:
number = 10
text = "20"
result = number + int(text)
print(result)
Output:
30
Python supports several common type conversion functions:
| Function | Purpose | Example |
|---|---|---|
int() |
Convert to integer | int("123") |
float() |
Convert to floating-point number | float("3.14") |
str() |
Convert to string | str(100) |
bool() |
Convert to boolean | bool(1) |
list() |
Convert to list | list("abc") |
tuple() |
Convert to tuple | tuple([1, 2]) |
set() |
Convert to set | set([1, 1, 2]) |
Type conversion does not always succeed:
int("hello")
This raises:
ValueError
Therefore, type conversion itself also requires consideration of exception handling and data validation.
8. Type Annotations: Adding Type Information to Dynamic Typing
The fact that Python uses dynamic typing does not mean that types cannot be expressed in code.
Starting from Python 3.5, Python has provided the syntactic foundation for expressing type information through type annotations (Type Hints).
For example:
def add(a: int, b: int) -> int:
return a + b
Here:
a: intindicates that parameterais expected to be an integer.b: intindicates that parameterbis expected to be an integer.-> intindicates that the function is expected to return an integer.
8.1 Type Annotations Do Not Automatically Enforce Type Checking
The following code can still run:
def add(a: int, b: int) -> int:
return a + b
print(add("Hello", "Python"))
Output:
HelloPython
This is because the Python interpreter does not, by default, perform full static type checking based on type annotations.
Type annotations mainly provide type information for use by developers, editors, IDEs, and static type checking tools.
8.2 Variable Type Annotations
name: str = "Alice"
age: int = 20
height: float = 1.68
is_active: bool = True
You can also declare just the type without assigning a value right away:
username: str
This form is mainly used to express the expected type of a variable; it does not immediately create an object with a value of that type.
8.3 Collection Type Annotations
Modern Python lets you use the built-in collection types directly for generic annotations.
names: list[str] = ["Alice", "Bob"]
scores: dict[str, int] = {
"Alice": 90,
"Bob": 85,
}
coordinates: tuple[float, float] = (10.5, 20.8)
tags: set[str] = {"python", "ai"}
This syntax has been supported since Python 3.9.