5
votes

I'm new to Python, and am trying to figure out if there is a way to specify the variable type in a parameter definition. For example:

def function(int(integer))

as opposed to:

def function(integer)
    int(integer)

I know it's not a major difference, but I'm trying to use good programming practices here, and if I'm defining a function with a large number of parameters, it could get messy.

3
Nope, there is no type checking in python, are you actually talking type checking or casting from something that can be cast to an int? - Padraic Cunningham
You question leads me to believe you aren't taking a Pythonic approach to solving your problem. Python is dynamically typed and your solution should be flexible to take advantage of that. - Dan
isinstance(some_variable, int) - Steven Rumbalski
Why do you need this? - Peter Wood

3 Answers

15
votes

As of Python 3.4 you can add type annotations to a function or method:

def function(a: int):
    pass

However these types are not enforced - you can still call the function with a value that is not an integer.

Furthermore, Python is based on the idea of duck typing so you may sometimes want to accept a variety of types, such as both int and float for a particular function.

14
votes

Python uses Duck typing which means you should not discriminate objects based on what type they are, but based on what attributes and functions they have. This has many advantages which are outside of the scope of this answer.

What you should do instead if you want to add documentation to your function is to use a docstring

def square(x):
    """takes a number and squares it"""
    return x**2

and type hints

def square(x: int) -> int:
    """takes a number and squares it"""
    return x**2

if you really need to check the arguments given to you, you can do a hasattr() to check for the attributes and functions the argument provides. In most situations (including this one) just not checking the type is better

def square(x):
    """takes a number and squares it"""
    if not hasattr(x, "__pow__"):
         raise TypeError("unsupported operand:", type(x))

    return x**2
6
votes

If you want to use the syntax

def function(a: int):
    pass

mentioned by @SimeonVisser and you have python3.5, you can use the decorator I wrote

from typing import get_type_hints

def strict_types(f):
    def type_checker(*args, **kwargs):
        hints = get_type_hints(f)

        all_args = kwargs.copy()
        all_args.update(dict(zip(f.__code__.co_varnames, args)))

        for key in all_args:
            if key in hints:
                if type(all_args[key]) != hints[key]:
                    raise Exception('Type of {} is {} and not {}'.format(key, type(all_args[key]), hints[key]))

        return f(*args, **kwargs)

    return type_checker

while defining functions like that

@strict_types
def concatenate_with_spam(text: str) -> str:
    return text + 'spam'

and it will raise an exception if the argument passed to your function is of the wrong type.

Traceback (most recent call last):
  File "strict_types.py", line 23, in <module>
    concatenate_with_spam(1)
  File "strict_types.py", line 13, in type_checker
    raise Exception('Type of {} is {} and not {}'.format(key, type(all_args[key]), hints[key]))
Exception: Type of text is <class 'int'> and not <class 'str'>

Though I haven't implemented a way to check the type of what you return and this solution won't suit you if you want to check it too.