Python course · Module 3: Object-Oriented Programming
Type hints - precise classification
In this lesson10
Welcome back! Darwin here with a lesson about precision and code documentation.
In biology, precise classification is key - "big animal" is not the same as "Panthera leo (African lion), male, adult, 190kg". In Python, type hints (type annotations) allow the same precision in code!
# Imprecise - what is this?
def count_animals(animals):
return len(animals)
# Precise - everything is clear!
def count_animals(animals: list[str]) -> int:
"""Count animals in the list"""
return len(animals)What are type hints?
Type hints are type annotations in Python - additional information about the types of variables, function parameters, and return values.
IMPORTANT: Type hints are optional and do NOT affect program execution! Python ignores them at runtime. They serve for:
- Documentation - explain the programmer's intentions
- IDE - better suggestions and autocomplete
- Tools - mypy, pyright can detect type errors
- Readability - easier to understand code
# Without type hints - we have to guess
def calculate_density(count, area):
return count / area
# With type hints - everything is clear!
def calculate_density(count: int, area: float) -> float:
"""Calculate population density (individuals/km²)"""
return count / areaBasic type hints
Variables
You write a variable annotation after a colon, between the name and the = sign. For containers you can also give the element type in square brackets:
# Basic types
name: str = "Lion"
age: int = 5
weight: float = 190.5
is_dangerous: bool = True
# Container types alone (no element types)
animals: list = ["Lion", "Elephant"]
habitat_map: dict = {"Lion": "savanna"}
# Python 3.9+ - even better with element types
animals: list[str] = ["Lion", "Elephant", "Giraffe"]
populations: dict[str, int] = {"Lion": 500, "Elephant": 300}
coordinates: tuple[float, float] = (51.5, -0.1)
unique_species: set[str] = {"Lion", "Elephant"}Functions - parameters and return type
In a function, you write the type of each parameter after a colon and the return type after the -> arrow, before the final colon:
def greet(name: str) -> str:
"""Takes str, returns str"""
return f"Hello, {name}!"
def add_numbers(a: int, b: int) -> int:
"""Takes two ints, returns int"""
return a + b
def calculate_average(numbers: list[float]) -> float:
"""Takes a list of floats, returns float"""
return sum(numbers) / len(numbers)
def print_info(message: str) -> None:
"""None means 'returns nothing' """
print(message)
# no return or return NoneTypes from the typing module
Optional - can be None
Optional[str] says that the function returns text or None. It is useful for a lookup that may find nothing:
from typing import Optional
def find_species(name: str) -> Optional[str]:
"""
Returns species or None if not found
Optional[str] = str | None
"""
database = {"Lion": "Panthera leo", "Elephant": "Loxodonta africana"}
return database.get(name) # May return str or None
result = find_species("Lion") # Optional[str]
if result is not None:
print(f"Found: {result}")Union - one of several types
Union lists several allowed types. An animal ID can be a number or text:
from typing import Union
def process_id(animal_id: Union[int, str]) -> str:
"""
Accepts int OR str
Python 3.10+: int | str
"""
return f"ID: {animal_id}"
process_id(123) # OK - int
process_id("LEO-45") # OK - strPython 3.10+: You can use | instead of Union!
def process_id(animal_id: int | str) -> str:
"""Newer syntax - Python 3.10+"""
return f"ID: {animal_id}"
# Optional can also be written shorter
def find_species(name: str) -> str | None:
"""str | None = Optional[str]"""
passList, Dict, Tuple, Set - with specific types
Built-in containers take their element types in square brackets. A tuple can have a fixed number of positions or any number, written as ...:
# Python 3.9+ - use lowercase!
def process_animals(names: list[str]) -> dict[str, int]:
"""List of strings → dictionary string:int"""
return {name: len(name) for name in names}
# Tuple - fixed number of elements with specified types
def get_coordinates() -> tuple[float, float]:
"""Returns (latitude, longitude)"""
return (51.5074, -0.1278)
# Tuple - variable number of elements of the same type
def get_observations() -> tuple[int, ...]:
"""Tuple with any number of ints"""
return (12, 45, 23, 67, 89)
# Set
def get_unique_habitats() -> set[str]:
"""Set of unique habitats"""
return {"savanna", "jungle", "mountains"}Any - any type
Any means the value can be of any type, so tools stop checking it:
from typing import Any
def log_data(data: Any) -> None:
"""Accepts anything - use sparingly!"""
print(f"Logging: {data}")
log_data(123) # OK
log_data("text") # OK
log_data([1, 2, 3]) # OK
log_data({"key": "val"}) # OKNote: Use Any only when you truly accept any type! It's like giving up on type hints.
Type hints for classes
In a class you annotate the class attributes, the parameters of __init__ and the methods, and the instance attributes. A class name that Python doesn't know yet goes in quotes, e.g. 'Species':
class Species:
"""Species with type hints"""
# Class attributes
kingdom: str = "Animalia"
all_species: list['Species'] = [] # Forward reference
def __init__(
self,
scientific_name: str,
common_name: str,
population: int,
endangered: bool = False
) -> None:
"""Constructor with type hints"""
self.scientific_name: str = scientific_name
self.common_name: str = common_name
self.population: int = population
self.endangered: bool = endangered
self.observations: list[dict[str, Any]] = []
Species.all_species.append(self)
def add_observation(
self,
location: str,
count: int,
date: str | None = None
) -> None:
"""Add observation - None return type"""
obs: dict[str, str | int] = {
"location": location,
"count": count
}
if date:
obs["date"] = date
self.observations.append(obs)
def get_population_trend(self) -> float:
"""Returns float"""
if len(self.observations) < 2:
return 0.0
first = self.observations[0]["count"]
last = self.observations[-1]["count"]
return (last - first) / first * 100
@classmethod
def get_endangered_species(cls) -> list['Species']:
"""Returns list of Species - forward reference!"""
return [s for s in cls.all_species if s.endangered]
@staticmethod
def is_valid_population(pop: int) -> bool:
"""Returns bool"""
return pop >= 0Advanced type hints
Callable - functions as types
When a parameter is a function, Callable[[Species], bool] describes what that function takes and what it returns:
from typing import Callable
def apply_filter(
species_list: list[Species],
filter_func: Callable[[Species], bool]
) -> list[Species]:
"""
Filter list by function
Callable[[Species], bool] = function taking Species, returning bool
"""
return [s for s in species_list if filter_func(s)]
# Usage
def is_endangered(species: Species) -> bool:
return species.endangered
endangered = apply_filter(Species.all_species, is_endangered)TypeAlias - aliases for complex types
You can name a long type once and use that name in many places. You create such an alias with the TypeAlias annotation:
from typing import TypeAlias
# Alias for readability
PopulationData: TypeAlias = dict[str, list[int]]
Coordinates: TypeAlias = tuple[float, float]
SpeciesDict: TypeAlias = dict[str, Species]
def analyze_populations(data: PopulationData) -> float:
"""The PopulationData type is more readable than dict[str, list[int]]"""
all_counts: list[int] = []
for counts in data.values():
all_counts.extend(counts)
return sum(all_counts) / len(all_counts)
def get_location(name: str) -> Coordinates:
"""Coordinates clearly states what we return"""
locations: dict[str, Coordinates] = {
"Serengeti": (-2.3333, 34.8333),
"Masai Mara": (-1.5, 35.1667)
}
return locations.get(name, (0.0, 0.0))Generic - generic classes
A generic class takes the element type as a parameter, just like list[str]. The same stack can hold strings or numbers, and the IDE still knows what you will take out of it:
from typing import Generic, TypeVar
T = TypeVar('T') # Generic type
class Stack(Generic[T]):
"""Generic stack - can store any type"""
def __init__(self) -> None:
self._items: list[T] = []
def push(self, item: T) -> None:
"""Add element of type T"""
self._items.append(item)
def pop(self) -> T:
"""Remove and return element of type T"""
return self._items.pop()
def is_empty(self) -> bool:
return len(self._items) == 0
# Usage
string_stack: Stack[str] = Stack[str]()
string_stack.push("Lion")
string_stack.push("Elephant")
animal: str = string_stack.pop() # IDE knows it's str!
int_stack: Stack[int] = Stack[int]()
int_stack.push(123)
int_stack.push(456)
number: int = int_stack.pop() # IDE knows it's int!Safari example - complete system with type hints
Now everything together: type aliases, enums for the conservation status and habitat, a class with annotations in every method, and helper functions that use it.
from typing import Optional, TypeAlias
from datetime import date
from enum import Enum
# === TYPE ALIASES ===
SpeciesID: TypeAlias = str
Coordinates: TypeAlias = tuple[float, float]
ObservationData: TypeAlias = dict[str, str | int | date]
# === ENUMS ===
class ConservationStatus(Enum):
"""Species conservation status"""
EXTINCT = "extinct"
EXTINCT_IN_WILD = "extinct_in_wild"
CRITICALLY_ENDANGERED = "critically_endangered"
ENDANGERED = "endangered"
VULNERABLE = "vulnerable"
NEAR_THREATENED = "near_threatened"
LEAST_CONCERN = "least_concern"
class Habitat(Enum):
"""Habitat type"""
SAVANNA = "savanna"
JUNGLE = "jungle"
MOUNTAINS = "mountains"
DESERT = "desert"
WETLANDS = "wetlands"
# === MAIN CLASS ===
class Species:
"""
Species class with full type hints
Precise classification like in biology!
"""
# Class attribute
_registry: dict[SpeciesID, 'Species'] = {}
def __init__(
self,
scientific_name: str,
common_name: str,
population: int,
habitat: Habitat,
status: ConservationStatus,
dangerous: bool = False
) -> None:
"""
Initialize species
Args:
scientific_name: Scientific name (e.g., "Panthera leo")
common_name: Common name (e.g., "Lion")
population: Number of individuals
habitat: Habitat type (enum)
status: Conservation status (enum)
dangerous: Whether dangerous to humans
"""
self.id: SpeciesID = scientific_name
self.scientific_name: str = scientific_name
self.common_name: str = common_name
self.population: int = population
self.habitat: Habitat = habitat
self.status: ConservationStatus = status
self.dangerous: bool = dangerous
# Observations list
self.observations: list[ObservationData] = []
# Locations
self.locations: set[Coordinates] = set()
# Register
Species._registry[self.id] = self
def add_observation(
self,
location: str,
coordinates: Coordinates,
count: int,
observation_date: date | None = None
) -> None:
"""
Add a species observation
Args:
location: Location name
coordinates: (latitude, longitude)
count: Number of observed individuals
observation_date: Observation date (optional)
"""
obs: ObservationData = {
"location": location,
"count": count,
"date": observation_date or date.today()
}
self.observations.append(obs)
self.locations.add(coordinates)
def get_total_observed(self) -> int:
"""Return total number of observed individuals"""
return sum(
int(obs["count"])
for obs in self.observations
)
def get_observation_locations(self) -> list[str]:
"""Return list of unique observation locations"""
locations: set[str] = {
str(obs["location"])
for obs in self.observations
}
return sorted(locations)
def is_threatened(self) -> bool:
"""Check if species is threatened"""
threatened_statuses: set[ConservationStatus] = {
ConservationStatus.CRITICALLY_ENDANGERED,
ConservationStatus.ENDANGERED,
ConservationStatus.VULNERABLE
}
return self.status in threatened_statuses
def get_risk_assessment(self) -> dict[str, str | int | bool]:
"""
Risk assessment for the expedition
Returns:
Dictionary with risk assessment
"""
risk_level: int = 0
if self.dangerous:
risk_level += 5
if self.population < 100:
risk_level += 3 # Rare - hard to find
if self.habitat == Habitat.JUNGLE:
risk_level += 2 # Difficult terrain
return {
"species": self.common_name,
"risk_level": min(10, risk_level),
"dangerous": self.dangerous,
"rare": self.population < 100,
"recommendation": "Extreme caution" if risk_level >= 7 else "Normal protocol"
}
@classmethod
def get_by_id(cls, species_id: SpeciesID) -> Optional['Species']:
"""
Find species by ID
Returns:
Species or None if not found
"""
return cls._registry.get(species_id)
@classmethod
def get_by_habitat(cls, habitat: Habitat) -> list['Species']:
"""Return all species from a given habitat"""
return [
species for species in cls._registry.values()
if species.habitat == habitat
]
@classmethod
def get_endangered(cls) -> list['Species']:
"""Return all threatened species"""
return [
species for species in cls._registry.values()
if species.is_threatened()
]
@staticmethod
def calculate_biodiversity_index(
species_list: list['Species']
) -> float:
"""
Calculate Simpson's biodiversity index
Args:
species_list: List of species to analyze
Returns:
Index (0.0 - 1.0, higher = greater diversity)
"""
if not species_list:
return 0.0
total: int = sum(s.population for s in species_list)
if total == 0:
return 0.0
sum_squares: float = sum(
(s.population / total) ** 2
for s in species_list
)
return 1.0 - sum_squares
def __str__(self) -> str:
return f"{self.common_name} ({self.population} individuals)"
def __repr__(self) -> str:
return (f"Species(scientific_name='{self.scientific_name}', "
f"population={self.population}, "
f"habitat={self.habitat.value})")
# === HELPER FUNCTIONS ===
def generate_report(species: Species) -> str:
"""
Generate a species report
Args:
species: Species to report on
Returns:
Formatted text report
"""
threatened: str = "YES" if species.is_threatened() else "No"
risk: dict[str, str | int | bool] = species.get_risk_assessment()
report: str = f"""
╔══════════════════════════════════════════════════╗
{species.common_name.upper()}
╠══════════════════════════════════════════════════╣
Scientific name: {species.scientific_name}
Population: {species.population} individuals
Habitat: {species.habitat.value}
Status: {species.status.value}
Threatened: {threatened}
Dangerous: {"YES" if species.dangerous else "No"}
Risk level: {risk['risk_level']}/10
Observations: {len(species.observations)}
Locations: {', '.join(species.get_observation_locations()) or 'None'}
╚══════════════════════════════════════════════════╝
""".strip()
return report
def filter_by_population(
species_list: list[Species],
min_pop: int,
max_pop: int | None = None
) -> list[Species]:
"""
Filter species by population
Args:
species_list: List of species
min_pop: Minimum population
max_pop: Maximum population (optional)
Returns:
Filtered list
"""
filtered: list[Species] = [
s for s in species_list
if s.population >= min_pop
]
if max_pop is not None:
filtered = [s for s in filtered if s.population <= max_pop]
return filtered
# === DEMONSTRATION ===
print("=== SPECIES CATALOG WITH TYPE HINTS ===\n")
# Creating species
lion = Species(
scientific_name="Panthera leo",
common_name="Lion",
population=120,
habitat=Habitat.SAVANNA,
status=ConservationStatus.VULNERABLE,
dangerous=True
)
rhino = Species(
scientific_name="Diceros bicornis",
common_name="Black Rhinoceros",
population=45,
habitat=Habitat.SAVANNA,
status=ConservationStatus.CRITICALLY_ENDANGERED,
dangerous=True
)
elephant = Species(
scientific_name="Loxodonta africana",
common_name="African Elephant",
population=450,
habitat=Habitat.SAVANNA,
status=ConservationStatus.ENDANGERED,
dangerous=False
)
# Add observations
lion.add_observation("Serengeti", (-2.3333, 34.8333), 12)
lion.add_observation("Masai Mara", (-1.5, 35.1667), 8)
rhino.add_observation("Ngorongoro", (-3.1792, 35.5500), 3)
elephant.add_observation("Amboseli", (-2.6527, 37.2606), 35)
# Reports
print(generate_report(lion))
print()
print(generate_report(rhino))
# Filtering
print("\n=== THREATENED SPECIES ===")
endangered: list[Species] = Species.get_endangered()
for species in endangered:
print(f" {species.common_name}: {species.status.value}")
# Filter by population
print("\n=== SPECIES WITH POPULATION < 100 ===")
rare: list[Species] = filter_by_population(
list(Species._registry.values()),
min_pop=0,
max_pop=99
)
for species in rare:
print(f" - {species.common_name}: {species.population} individuals")
# Biodiversity index
biodiversity: float = Species.calculate_biodiversity_index(
list(Species._registry.values())
)
print(f"\nBiodiversity index: {biodiversity:.3f}")Tools for type checking
mypy - static type checking
The mypy tool reads the annotations and checks the types before you run the program. You install it with pip and point it at the file to check:
# Installation
pip install mypy
# Check a file
mypy script.pyPython runs this code without an error, but mypy stops it:
def add(a: int, b: int) -> int:
return a + b
result: str = add(5, 10) # mypy: Incompatible types in assignmentThe function returns int, but the variable is declared as str. Python doesn't check annotations while the program runs, so only mypy or your editor will catch this mistake.
Type checking in IDEs
Modern IDEs (VS Code, PyCharm) automatically check type hints:
- Autocomplete - suggestions based on types
- Error detection - detecting type errors
- Refactoring - safer changes
- Documentation - quick signature preview
Type hints best practices
1. Always add type hints to public APIs
Methods that the rest of the program uses are a contract with other programmers. Annotations tell right away what those methods expect and what they return:
# Good - public API with type hints
class Species:
def add_observation(self, location: str, count: int) -> None:
pass
# Bad - public API without types
class Species:
def add_observation(self, location, count):
pass2. Use specific types instead of Any
Any tells the reader nothing and checks nothing. If you know what data comes in, write it in the annotation:
# Bad - too generic
def process_data(data: Any) -> Any:
return data
# Good - specific types
def process_data(data: dict[str, int]) -> list[int]:
return list(data.values())3. Use Optional for None values
If a function can return None, say so in the annotation. Then everyone who calls it knows they have to check the result:
# Good - clearly specified
def find_species(name: str) -> Species | None:
pass
# Misleading - does it return None?
def find_species(name: str) -> Species:
pass4. Document complex types with TypeAlias
When the same complex type appears in several places, give it a name. The function signature gets shorter and its meaning is clear at once:
# Readable
ObservationData: TypeAlias = dict[str, str | int | date]
def add_observation(data: ObservationData) -> None:
pass
# Unreadable
def add_observation(data: dict[str, str | int | date]) -> None:
passSummary
In this lesson you learned:
- What type hints are and why to use them
- Basic annotations: int, str, float, bool, list, dict
- Optional and Union (and the
|syntax in Python 3.10+) - Type hints for functions (parameters and return types)
- Type hints for classes and methods
- Advanced techniques: Callable, TypeAlias, Generic
- Enums for safe values
- Tools like mypy
- Type hints best practices
Checkpoint
Before moving on:
- You understand the difference between type hints and runtime behavior
- You can add type hints to functions
- You know Optional and Union (and
|) - You know how to use list[T], dict[K, V]
- You understand TypeAlias and Generic
Safari Analogy: Type hints are like precise biological classification - instead of "big cat" we say "Panthera leo, male, 5 years, 190kg" - everything is clear!
In the next lesson Darwin will teach you decorators - a powerful tool for modifying function and class behaviors!
Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. Type hints in Python are:
2. How do you annotate a function's return type?
Hands-on tasks in the game
- Vertical ordering
Arrange the typical elements of a class definition:
- Code editor
Create an Animal class with type hints: name: str, age: int, weight: float
- Horizontal ordering
Arrange the header of a speak method that returns text (type hint str):