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.

Jessica
  • 2,003
  • 2
  • 18
  • 33
  • 2
    You might want to take a look at [this question ("Is Python strongly typed?")](http://stackoverflow.com/questions/11328920/is-python-strongly-typed), and [this one ("Function parameter types in Python")](http://stackoverflow.com/questions/2489669/function-parameter-types-in-python) as well. – Greg Sadetsky May 16 '16 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](https://docs.python.org/3/library/typing.html), as you are using, but static typing and function overloading are more Java tools than Python tools. – TigerhawkT3 May 16 '16 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`. – user2357112 supports Monica May 16 '16 at 18:55
  • Check out type hinting in PyCharm, it can show warnings as you're writing the code. – Alex Hall May 16 '16 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. – Ella Rose May 16 '16 at 21:28

1 Answers1

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.

Community
  • 1
  • 1
Ella Rose
  • 486
  • 7
  • 15