How does Python handle function parameter types?

How do Python function parameter types work when passing arguments?

When you create a function in Python like this:

def my_func(param1, param2):
    # stuff

You don’t specify the types of param1 and param2. However, Python is considered a strongly typed language, so it seems like Python shouldn’t allow passing a parameter of the wrong type. How does Python handle this? Does it check if the parameter types match the function’s intended types, and what happens if you pass in a different type? Will the program just fail when the parameter is used, or do you need to explicitly specify the type to avoid such issues?

I’ve been working with Python for quite some time, and one thing that stands out is its flexibility with types. Python doesn’t enforce strict type checks when defining functions because of its dynamic typing. It uses the concept of ‘duck typing’—if it walks like a duck and quacks like a duck, it’s a duck.

Here’s a simple example:

def add_numbers(a, b):
    return a + b  # Works as long as "+" is supported

This means you can pass integers, strings, lists, or anything else that supports the + operator. Python will happily run it, relying on the object’s behavior rather than its type.

That’s a great starting point, Ishrath. If you’re looking to add some clarity or structure to your code, Python introduced type annotations. While Python won’t enforce these types at runtime, they help with documentation and allow static type checkers like mypy to catch potential issues before execution.

For instance:

def add_numbers(a: int, b: int) -> int:
    return a + b

This hints that a and b are expected to be integers and that the function will return an integer. Static analysis tools will flag issues if you pass incompatible types, though Python itself will only raise errors during runtime if the operation fails. It’s a way to bridge Python’s flexibility with added safeguards.

Both approaches are useful, but what if you want stricter control during runtime? You can take it a step further with isinstance() checks to validate parameter types explicitly.

Here’s how:

def add_numbers(a, b):
    if not isinstance(a, int) or not isinstance(b, int):
        raise TypeError("Both parameters must be integers")
    return a + b

This ensures that the parameters are integers before proceeding. It’s especially helpful when you want to prevent misuse early in execution, particularly in larger or more complex systems where incorrect types might cause downstream issues.