Is there a way to get number of args a method takes, if we just have method name in string type?

Viewed 51

First of all, I am using python 2.7.13 so I have very limited options. I tried:

@some_decorator
def xyz(self,a,b,c):
    pass
function_name = " xyz"    
inspect.getargspec(getattr(self,function_name))

and it gives:

ArgSpec(args=[], varargs='args', keywords='kwargs', defaults=None)

Its giving 0 args because of the decorator. If I try on other methods, its giving correct list of arguments.

1 Answers

One of the solutions can be using ast module:

import ast    
def GetAllMethodsArgs(self):
    with open(os.path.abspath(__file__)) as file:
        node = ast.parse(file.read())

    classDefinitions = [n for n in node.body if isinstance(n, ast.ClassDef)]
    for classDef in classDefinitions:
        functions = [n for n in classDef.body if isinstance(n, ast.FunctionDef)]

    for function in functions:
        self.methodArgsdict[function.name] = len(function.args.args)

Call this in the init of the class, after defining methodArgsdict = {}. This function will fill the dictionary with the name of the function as key and arguments it takes as its value.

Related