【问题标题】:How can I print the function head, including name, arguments, and docstring?如何打印函数头,包括名称、参数和文档字符串?
【发布时间】:2015-04-01 20:53:57
【问题描述】:

假设我有以下内容:

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。

【问题讨论】:

    标签: function python-3.x


    【解决方案1】:

    是的!您可以使用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)
    

    打印:

    foo(arg1, arg2, arg3=None, *args, **kwargs)
    这个功能真的很酷。

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

    【讨论】:

      【解决方案2】:

      您可以使用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.
      

      【讨论】:

        猜你喜欢
        • 2013-08-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多