문제

I have been creating my own python file in which I create functions that I can call upon when plotting. This way I only have to load in one file with all kinds of functions that I can use to tweak my results, keeping my code simple.

What I want to know is whether it is possible to return which arguments a function is missing and if so how to implement this?

To illustrate what I mean, I define the following function:

def func(integer, float):
    return integer / float

If I now would call the function like:

print func(2)

it will give the error which states it requires two arguments and one is missing.

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

Since I will be expanding my tweak file over the years I will be forgetting some of the functions and the required arguments. Therefore I would like to be returned an error which states the names of the arguments.

So in the case of the example I would like to be returned something like:

TypeError: func(integer, float) takes exactly 2 arguments (1 given)

I don't even really care about the number of arguments that are required or are given. All I really need is just func(integer, float) in the case I am missing an argument or giving one too many.

Is this possible?

Thanks in advance!

도움이 되었습니까?

해결책 3

After playing around I found the answer that satisfies me the most:

import sys
import numpy

def func(integer = float("nan"), number = float("nan")):
    if numpy.isnan(integer):
        print "Function syntax: func(integer, number)"
        sys.exit()
    return integer * number

func()
>>> Function syntax: func(integer, number)

func(1)
>>> nan

func(3,2)
>>> 6

By setting my function variables to NaN I can only override them by actually giving them a value when calling the function. However, due to the if statement I can actually print the function variables by not giving any when calling it.

다른 팁

I don't think you would ever want to really do this - but I guess one hacky approach would be use getargspec() from the inspect module to determine the "names and default values of a Python function’s arguments.", and then wrap all function calls in try/except blocks.

>>> try:
        func(2):
    except TypeError as e:
        print "Error! The function expected {} args".format(getargspec(func).args)
        raise e
Error! The function expected ['integer', 'float'] args 
Traceback (most recent call last):
File "<input>", line 5, in <module>
TypeError: func() takes exactly 2 arguments (1 given)

You could maybe wrap that into a custom exception too, which subclasses TypeError (although here we are assuming that the TypeError is being raised because the function wasn't passed the correct number of arguments which might be a bit of an over-simplification).

Note that you can't add code to do this inside the function object itself, as Python raises the TypeError exception before it executes any of the code in the function body.

>>> def another_func(arg1):
        print "Got inside the function - the arg was {}".format(arg1)
>>> another_func("hello")
Got inside the function - the arg was hello
>>> another_func()
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: another_function() takes exactly 1 argument (0 given)

I finally managed to write this code, I hope it helps:

import inspect, traceback

def func(integer, float):
    return integer / float

if __name__ == "__main__":
    try:
        func(2)
    except TypeError:
        print "ERROR: 'func(a, b)' . a is an integer and b is a float"
        print traceback.format_exc()

Output:

ERROR: 'func(a, b)' . a is an integer and b is a float Traceback (most recent call last):
File "c:/a/script.py", line 9, in func(2)
TypeError: func() takes exactly 2 arguments (1 given)

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top