0
0
PythonHow-ToBeginner · 3 min read

How to Use Type Hints in Python: Simple Guide with Examples

In Python, use type hints by adding a colon and the expected type after variable names or function parameters, and use -> to specify the return type of functions. This helps make your code clearer and easier to read without changing how it runs.
📐

Syntax

Type hints in Python use a simple syntax to show what type a variable or function parameter should be. You add a colon : after the variable name followed by the type. For functions, you add -> after the parameters to show the return type.

  • Variable: variable_name: type
  • Function parameter: def func(param: type):
  • Function return: def func() -> type:
python
def greet(name: str) -> str:
    return 'Hello, ' + name

age: int = 25
💻

Example

This example shows a function with type hints for its parameter and return value, and a variable with a type hint. It prints a greeting message and the age.

python
def greet(name: str) -> str:
    return 'Hello, ' + name

age: int = 30

print(greet('Alice'))
print(f'Age is {age}')
Output
Hello, Alice Age is 30
⚠️

Common Pitfalls

Type hints do not enforce types at runtime; they are only for readability and tools like linters or IDEs. A common mistake is to expect Python to stop wrong types automatically, but it won't. Also, avoid using complex types without importing them from the typing module.

python
def add_numbers(a: int, b: int) -> int:
    return a + b

# This will run but is not type safe
result = add_numbers('2', 3)  # Wrong types but no error at runtime

# Correct usage
result = add_numbers(2, 3)
📊

Quick Reference

Here is a quick summary of common type hints:

Type HintMeaning
intInteger numbers
strText strings
floatDecimal numbers
boolTrue or False values
list[int]List of integers
dict[str, int]Dictionary with string keys and integer values
Optional[str]Value can be string or None (needs import from typing)

Key Takeaways

Use type hints by adding a colon and type after variables and function parameters.
Specify function return types with an arrow (->) before the colon.
Type hints improve code clarity but do not enforce types at runtime.
Use the typing module for complex types like Optional or List.
Tools like linters and IDEs can check type hints to catch errors early.