History of the issue:
Dynamic typing has been characteristic of Python since its early versions. This means that variables are not bound to a specific data type in advance, unlike languages such as Java or C++. The type is determined at runtime.
Problem:
The main difficulty is the loss of explicit control over types. This complicates error detection at the code-writing stage, which can lead to logical bugs at runtime, especially when scaling the code.
Solution:
Python addresses this problem through duck typing (if an object behaves like a duck, then it's a duck) and also through type annotations (type hints). However, annotations are not mandatory and are not checked during execution, only by external tools.
Example code:
x = 42 # int x = "foo" # now a string def process(val): return val + val print(process(5)) # 10 print(process("ha")) # haha
Key features:
Is it possible to use one variable first as a list and then as a number in one block of code, and will this lead to a syntax error?
Yes — there will be no syntax error. The error will occur only when trying to perform an invalid operation with the new type.
x = [1, 2, 3] x = 5 # print(x[0]) # Error will occur only on this call
Does a type hint in Python guarantee that a variable will always have the specified type at runtime?
No — a type hint is just a suggestion, the interpreter does not check it. Only linters and mypy can check types.
def foo(x: int) -> int: return x + 1 foo("string") # there will be no error until the call
Is the function type also dynamic? Can the function signature be changed at runtime?
A function is a first-class object. Its type can be redefined, but the signature cannot (you can replace the function with a new one).
def f(): return 5 f = lambda: "abc" print(f()) # 'abc'
Negative case
In one project, the types of the function parameters were not checked, leading to user form data arriving as strings, while working with them as numbers. Unpredictable errors occurred in production.
Pros:
Rapid prototyping, short functions, little boilerplate.
Cons:
Difficult debugging, errors appear in the most unexpected places and only with certain data.
Positive case
When using type hints and static type validation with mypy, problems were detected in the CI/CD stage before going to production.
Pros:
Early detection of potential issues, easy maintainability of code.
Cons:
Time spent on additional checks, sometimes a bit of extra code is added.