2015-04-01 30 views
3

说我有以下几点:如何打印函数头,包括名称,参数和文档字符串?

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

我如何定义一个新的功能functionprinter(f),使functionprinter(f)将打印

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

或类似这种事情?我已经知道foo.__name__foo.__doc__并且已经看到了inspect模块,具体在这里:Getting method parameter names in python但似乎无法将所有内容串在一起,特别是默认参数正确打印。我正在使用Python 3.4.1。

回答

2

是!您可以与inspect模块:

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) 

打印:

富(ARG1,ARG2,ARG3 =无,* ARGS,** kwargs)
这个功能真的很酷。

请注意,我改变了你default参数None只是为了这个演示,因为我没有定义的变量default

1

您可以使用inspect.signature(来代表一个可调用对象的调用签名和返回注释)和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. 
相关问题