Sobes.tech
Junior

What type of typing does Python have: static or dynamic?

sobes.tech AI

Answer from AI

Dynamic, but with static elements thanks to type annotations.

In dynamic typing, the variable type is determined at runtime based on the assigned value.

# Dynamic typing: x can take different data types
x = 10  # int
x = "hello" # str

Since Python 3.5, type annotations (type hints) have been added, allowing you to specify the expected type of a variable, function argument, or return value. This does not make Python a statically typed language in the traditional sense, but it allows static code analyzers (like mypy) to check types before runtime.

# Type annotations
def greet(name: str) -> str:
    return f"Hello, {name}"

age: int = 30

Main differences between dynamic and static typing:

Characteristic Dynamic typing Static typing
Type definition During runtime During compilation
Type error checking During runtime During compilation
Flexibility Higher Lower
Performance May be lower (due to checks during execution) Usually higher (types known in advance)

Despite annotations, Python remains a dynamically typed language, as type checking still occurs at runtime, and a variable can be assigned a value of a different type even if there was a syntactic annotation. Annotations serve to improve code readability, facilitate debugging, and enable static analysis tools.