Python - Data Typing [part I]
“The type system aims to provide a standard syntax for type annotations, opening up Python code to easier static analysis and refactoring, potential runtime type checking, and (perhaps, in some contexts) code generation utilizing type information.
The type system was originally specified in a series of PEPs, starting with PEP 484.” - Python.org1
Typing
Different programming languages have strong or weak typing, static or dynamic typing, and explicit or implicit typing.
Typing in Python
Python has strong, dynamic, and implicit typing system.
-
Strong: Variables of different types cannot be combined, and an error (
TypeError
) is thrown if attempted.
Example:"string" + number
>>> "John" + 1 .. TypeError: Can only concatenate str (not "int") to str
-
Dynamic: The type of the variable is defined at runtime according to the assigned value.
Example:name = "John" # string number = 1 # integer value = 5.8 # decimals
-
Implicit: It is unnecessary to declare the variable type, as Python automatically identifies it.
Example:value = "John" # string value = 1 # integer value = 5.8 # decimals
For each assignment, the type is auto-redefined.
Note: There is a type identification feature in Python 3.5 or higher; for now,
it does not affect the interpreter’s behavior.
This is to make the code easier to read or to autocomplete in IDEs.
Example:
name: str = "John"
number: int = 1
value: float = 5.8
n_list: list = [1,2,3,4,5,6]
Referencies
-
The Python Type System https://typing.python.org/en/latest/spec/type-system.html ↩︎