Function Return Types

Function Return Types in Python.

Python - Function Return Types:

Functions can have return types, although Python is dynamically typed, meaning you don't specify the return type explicitly in the function signature like in statically typed languages such as C or C++. Instead, Python infers the return type based on the values returned by the function.

However, you can use type hints to indicate the expected return type of a function. Although this is not enforced by the interpreter, it can be used by development tools and static analysis tools to check for potential type errors.

Here's an example of using type hints for return types in Python:

PDF Copy Code
# Python function: Return Types
def add(a: int, b: int) -> int:
    return a + b

result = add(3, 5)


'a: int' and 'b: int' indicate that the parameters 'a' and 'b' are expected to be integers.

'->' int indicates that the function is expected to return an integer.

However, it's important to note that Python doesn't enforce these types at runtime, so you can still return values of different types than specified. It's more of a convention and a tool for code readability and maintainability rather than strict enforcement.

Starting from Python 3.9, you can use Literal to specify exact return types. For example:

PDF Copy Code
# Python function: Literal
from typing import Literal

def get_status() -> Literal["success", "error"]:
    # Some logic to determine status
    return "success"

status = get_status()

Here, the function 'get_status()' is expected to return either "success" or "error", and using 'Literal', you explicitly specify these possible return values.

What's Next?

We actively create content for our YouTube channel and consistently upload or share knowledge on the web platform.