Rima brings up a great point about type hints. To take it further, Python’s standard library includes the typing module, which provides advanced type hinting capabilities like Union, Optional, and Callable. These allow you to handle more complex scenarios elegantly.
For example:
from typing import Union
def process_data(data: Union[int, str]) -> str:
if isinstance(data, int):
return f"Processed number: {data}"
elif isinstance(data, str):
return f"Processed text: {data}"
print(process_data(42)) # "Processed number: 42"
print(process_data("hi")) # "Processed text: hi"
Using such features helps make your code more robust and developer-friendly, especially in larger projects. This balance between Python’s flexibility and optional type safety is one of the reasons it’s so widely loved.