0

Currently Python allows you to define functions like

def f(x, A): 

I would like to be able to define functions like

def f(x: int, A: list): 

because I think it would cut down on programmer errors.

How can I do this?

Right now I am resorting to

def f(x, A): assert type(x) == int and type(A) == list, "Invalid parameters to function f" 

But I think it might be easier if I could just change the signature of the def function.

5
  • 2
    You might want to take a look at this question ("Is Python strongly typed?"), and this one ("Function parameter types in Python") as well. Commented May 16, 2016 at 18:41
  • 1
    Assertions can be turned off. You shouldn't rely on them for program flow. Also, Python does include functionality for type hinting, as you are using, but static typing and function overloading are more Java tools than Python tools. Commented May 16, 2016 at 18:48
  • 1
    def is not a function. It doesn't have a signature, and you can't change how it works any more than you could change return or while. Commented May 16, 2016 at 18:55
  • Check out type hinting in PyCharm, it can show warnings as you're writing the code. Commented May 16, 2016 at 19:22
  • @user2357112 You certainly can change the functionality of any keyword via source code preprocessing. However, that'd be like using a nuclear bomb to go grocery shopping. It's just going to be a disaster and dinners never going to happen. Commented May 16, 2016 at 21:28

1 Answer 1

1

Modifying def is possible, but not at all the right (simplest) approach.

The easiest way will be to use python 3. It supports the type annotations, though it does not do anything with them by default.

This answer combines python 3's annotations with a decorator and type filtering helper functions. There are plenty of decorator based solutions and recipes for type checking. Do a search for "python annotation type checking" if you want other examples.

Note that the above question includes answers with decorators for python 2 as well, if you cannot use python 3 for some reason.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.