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

165 Views Asked by At

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) 
3

There are 3 best solutions below

1
On BEST ANSWER

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))) 
0
On

wouldn't you be able to do it with a formated string?

argstr = args[0]
  for arg in args[1:]:
    argstr +=', {}'.format(arg)
repstr='{}({})'.format(name, argstr)
0
On
import inspect

def fn_signature(func_obj):
    out = func_obj.__name__
    
    try:
        signature = inspect.signature(func_obj)
    except (ValueError, TypeError):
        signature = None

    if signature is not None:
        out += f"{signature}\n"
        
    return out