1

I want to validate if python function calls are valid without executing them.

Let's say I have the following code:

def func(a, b):
    print(a, b)

cond = True

if cond:
    func(1, 2)
else:
    func(1)

If cond = True, then everything will run just fine, but if cond = False, then it will fail throwing the following error:

TypeError: func() takes exactly 2 arguments (1 given)

I need to know if all function calls are valid, without having to call any function.

Vinay Sharma
  • 164
  • 1
  • 7
  • Are you able to run unittests? – Frank Oct 18 '19 at 13:55
  • A proper static analyser would catch this kind of problem. Unit tests would catch this if properly written to test all conditions. Why is this something you need to figure out at runtime, and what would you do if you found a problem? – deceze Oct 18 '19 at 13:56
  • 1
    The Python way tends to be "Better to ask for Forgiveness than Permission" - just make the call and if it doesn't work, we'll handle it. However, if it's really the code up there then it's just a structural error in your code. You'd need to give more ("real") code for us to give a proper answer about how to handle this situation. – Gloweye Oct 18 '19 at 13:59
  • I don't want to run the hypothetical checker at runtime, instead just check before runtime to see if anything might fail at runtime. Anyways, I found a solution using mypy (Python's static type checker) – Vinay Sharma Nov 19 '19 at 15:42

1 Answers1

2

Such errors can be checked beforehand using mypy.

  1. Install mypy python3 -m pip install -U mypy.
  2. For checking Python3 code run mypy code.py, and for Python2 run mypy --py2 code.py.
  3. It will throw the following error:
code.py:9: error: Too few arguments for "func"
Found 1 error in 1 file (checked 1 source file)
Vinay Sharma
  • 164
  • 1
  • 7