pythonfunctionpython-3.7inspectfunction-signature

How to get a clean function signature in python as seen in the codebase?


I have the following code to get the function signature using inspect to print it to the terminal in Python

import inspect

def foo(a, b):
   # do something
   return ans

func_rep = foo
name = func_rep.__name__   # 'foo'
args = inspect.getfullargspec(func_rep).args  # ['a', 'b']
repstr = name + f'{str(tuple(args))}'
print(repstr)   # foo('a', 'b')

As seen above, the output of the representation has func_args in single quotes 'a'.

How can I get an output as follows in terminal ? or in an imported codebase ?

foo(a,b) 

Solution

  • This code will print the function signuature without single quotes(').

    import inspect
    
    def foo(a, b):
       # do something
       return ans
    
    func_rep = foo
    name = func_rep.__name__   # 'foo'
    args = inspect.getfullargspec(func_rep).args  # ['a', 'b']
    print(name+'(%s)'%','.join(map(str, args)))