3

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.

  • I am not entirely sure and this sounds too simple but, it seems that ```function_name``` has an extra blank space. Probably it should be ```function_name = "xyz"``` but I am not sure, just guessing here. – EnriqueBet Mar 27 '20 at 07:12
  • @EnriqueBet, sorry that was just for an example and a typo while posting this question. Correcting it. – karan patel Mar 27 '20 at 07:22
  • Sorry about that, I was almost certain it was a typo but I had to give it a try. Hopefully, someone will help you with this, it is an interesting problem. Why do you need to get the number of args given by each function? – EnriqueBet Mar 27 '20 at 07:28
  • based on the number of args the method takes, I need to call that method by passing either 3 args or no args. All the methods in the call are either with 3 args or no arg. – karan patel Mar 27 '20 at 07:35
  • Yes, the decorator is taking the hit from `inspect`, rather than `xyz`. Do you have a way to bypass the decorator - [such as this post](https://stackoverflow.com/q/9702219/6340496)? – S3DEV Mar 27 '20 at 11:18
  • Thanks @S3DEV, this can be one of the probable solutions. – karan patel Mar 27 '20 at 12:57

1 Answers1

0

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.