Functions III Type Hints

Type Hinting in Python Functions

Type Hinting in Python Functions

As you start to write more complex Python code, you might have come across function definitions that include syntax like : str or -> int. These are examples of type hinting, a feature introduced in Python 3.5 as part of PEP 484. Type hints make your code more explicit and easier to understand. They can also help with debugging and allow some IDEs and tools to provide better autocompletion and linting.

1. Basic Type Hints

The most basic type hints are straightforward. Just add a colon and the type after the parameter name in the function definition. You can do the same for the return type by adding -> type before the final colon. Here's an example:

    def greet(name: str) -> str:
        return f'Hello, {name}!'

In this example, we're saying that the name parameter should be a string, and the function will return a string.

2. Complex Type Hints

You can use type hints with complex types as well. For instance, if a function takes a list of integers as a parameter, you could use List[int] as the type hint. Note that for these complex types, you need to import them from the typing module. Here's an example:

    from typing import List

    def double_numbers(numbers: List[int]) -> List[int]:
        return [x * 2 for x in numbers]

3. Optional Types

If a parameter could be of several different types, you can use the Union type hint to specify this. If a parameter might be None, you can use the Optional type hint, which is equivalent to Union[T, None]. Here's an example:

    from typing import Optional

    def greet(name: Optional[str] = None) -> str:
        if name is None:
            return 'Hello, world!'
            return f'Hello, {name}!'

4. The Any Type

If a function can accept any type, or returns a value of any type, you can use the Any type hint. Use this sparingly, as it can make your code harder to understand:

    from typing import Any

    def print_arg(arg: Any) -> None:

Remember, type hints are not enforced by Python. They're just hints!


Popular posts from this blog

Drawing Tables with ReportLab: A Comprehensive Example

Blog Topics

DataFrame groupby agg style bar