Python — Type Hints

Tony
5 min readApr 8, 2024

Why Type Hints

Python is characterized by dynamic typing, setting it apart from statically typed languages such as C/C++ and Java. In statically typed languages, variables must be explicitly declared with a specific type before they’re assigned a value. Throughout the runtime of a C/C++/Java program, a variable can only hold data of its predetermined type.

However, Python, being a dynamically typed language, has always offered us flexibility in not requiring explicit variable type declaration. Here are a few examples that you can try out in a Python interactive shell or script:

# Define a variable
x = 10
print(type(x)) # Outputs: <class 'int'>

# Now assign a string to the same variable
x = "Hello, World!"
print(type(x)) # Outputs: <class 'str'>

# Now assign a float to the same variable
x = 3.14
print(type(x)) # Outputs: <class 'float'>

# Now assign a list to the same variable
x = [1, 2, 3]
print(type(x)) # Outputs: <class 'list'>

In the above example, x starts as an integer (int), then becomes a string (str), then a float (float), and finally a list (list). The type() function is used to print the type of x at each step.

While this has its advantages, it can also lead to potential bugs and errors, especially in large codebases or when working with teams. For example:

--

--