Type hints make expectations visible.
When you read a function without hints, it is not always clear which values it expects or returns.
def izracunaj_cenu(cena, popust):
return cena - cena * popust / 100
def izracunaj_cenu(cena: float, popust: float) -> float:
return cena - cena * popust / 100The algorithm did not change. float describes the expected parameters, and -> float describes the expected return value.
Common basic hints are int for whole numbers, float for decimal numbers, str for text, and bool for True or False.
Important: Python does not enforce type hints during normal execution. An annotation is useful information, not automatic runtime validation.
def napravi_pozdrav(ime: str) -> str:
return f"Zdravo, {ime}!"
def prikazi_poruku(poruka: str) -> None:
print(poruka)
ime: str = "Ana"
godine: int = 20
ocene: list[int] = [8, 9, 10]
cene: dict[str, float] = {"Hleb": 85.0}A parameter hint describes input. The hint after -> describes the result. None means that a function performs an action but does not return a useful value. Collection hints describe the values inside a list or dictionary.
def pronadji_korisnika(korisnik_id: int) -> str | None:
...
vrednost: int | float = 12.5str | None means the result can be text or no result. int | float accepts either kind of number. The | union syntax requires Python 3.10 or newer.
class Proizvod:
def __init__(self, naziv: str, cena: float) -> None:
self.naziv = naziv
self.cena = cena
def prikazi(self) -> str:
return f"{self.naziv}: {self.cena} RSD"This connects type hints with OOP. In this simple example, self does not need its own explicit hint.
What type hints do not do
- They do not reject every wrong valueA function can still receive a value with the wrong type. A real error can happen later when Python performs an incompatible operation.
- They do not convert valuesA
strhint does not automatically turn a number into text, and aninthint does not turn text into a number. - They do not replace testing or reasoningCorrect hints cannot prevent logical errors. VS Code, Pylance, or static-analysis tools can warn about possible mismatches depending on their configuration, but that is not runtime validation.
Before asking Sloby for help
- Expected type is not a guaranteeAsk what Python actually does with the supplied value at runtime.
- Return type is unclearLook for every return path, then decide whether the function returns a value or None.
