71. Python Type Hints - MantsSk/CA_PTUA14 GitHub Wiki
Introduction to Static Typing in Python
Python is a dynamically typed language, meaning you don't have to declare the type of a variable when you write your code. However, since Python 3.5, the language has supported optional static typing using type hints. Static typing can help catch errors early, improve code readability, and aid in code completion and linting by IDEs.
Basic Type Annotations
1. Variables
To specify the type of a variable, you can use a colon followed by the type.
age: int = 25
name: str = "Alice"
height: float = 5.7
is_student: bool = True
2. Functions
Type hints can also be used to specify the types of function arguments and return values.
def greet(name: str) -> str:
return f"Hello, {name}"
def add(a: int, b: int) -> int:
return a + b
3. Lists and Dictionaries
For more complex types like lists and dictionaries, you can use the typing module.
from typing import List, Dict
numbers: List[int] = [1, 2, 3]
grades: Dict[str, int] = {"Alice": 90, "Bob": 85}
4. Optional Types
If a variable can be of a certain type or None, use Optional.
from typing import Optional
def find_name(name_id: int) -> Optional[str]:
# Simulated lookup
if name_id == 1:
return "Alice"
return None
5. Union Types
When a variable can be multiple types, use Union.
from typing import Union
def get_value(value: Union[int, str]) -> str:
return str(value)