3

Say I have the following:

def foo(arg1, arg2, arg3 = default, *args, *kwargs*):
    """This function is really cool."""
    return

How can I define a new function functionprinter(f) so that functionprinter(f) would print

foo(arg1, arg2, arg3 = default, *args, *kwargs*)
This function is really cool.

or something of that nature? I already know foo.__name__ and foo.__doc__ and have seen the inspect module, specifically here: Getting method parameter names in python but can't seem to string together everything, in particular having the default arguments print properly. I am using Python 3.4.1.

Community
  • 1
  • 1
Abe Schulte
  • 133
  • 3

2 Answers2

2

Yup! You can with the inspect module:

import inspect

def foo(arg1, arg2, arg3=None , *args, **kwargs):
    """This function is really cool."""
    return

def functionprinter(f):

    print("{}{}".format(f.__name__, inspect.signature(f)))
    print(inspect.getdoc(f))

functionprinter(foo)

Prints:

foo(arg1, arg2, arg3=None, *args, **kwargs)
This function is really cool.

Note that I changed your default argument to None just for this demonstration because I didn't have the variable default defined.

skrrgwasme
  • 9,358
  • 11
  • 54
  • 84
1

You can use inspect.signature (to represents the call signature of a callable object and its return annotation.) and inspect.getdoc :

>>> print(inspect.signature(foo))
(arg1, arg2, arg3=3, *args, **kwargs)
>>> inspect.getdoc(foo)
'This function is really cool.'

>>> print ('\n'.join((foo.__name__+str(inspect.signature(foo)),inspect.getdoc(foo))))
foo(arg1, arg2, arg3='', *args, **kwargs)
This function is really cool.
Mazdak
  • 105,000
  • 18
  • 159
  • 188