In Python, you can specify the input types and return type of a function using type hints. Type hints provide a way to indicate the expected types of function arguments and the return type of the function. While type hints are not enforced at runtime, they can be used by static type checkers (like mypy
) to catch potential type-related errors and by IDEs
to provide better code suggestions.
Here's how you can specify the input types and return type of a function using type hints:
def add_numbers(x: int, y: int) -> int:
return x + y
result = add_numbers(3, 5) # This is valid
result = add_numbers('3', '5') # This will raise a TypeError at runtime
def greet(name: str) -> str:
return f"Hello, {name}!"
message = greet("Alice") # This is valid
message = greet(123) # This will raise a TypeError at runtime
You can use built-in types (like int
, str
, float
, bool
, etc.) or custom types as type hints. You can also use Union (Union[int, float]
), Tuple (Tuple[int, str]
), List (List[str]
), Dict (Dict[str, int]
), etc., for more complex type hints.
Example using lists and dictionaries
from typing import Dict, Any, List, Tuple
def getMetadata(book: Tuple[int, str]) -> Dict[str, Any]:
return {
'param1': book
'param2': {
'foo':'bar'
}
}