首页 > 解决方案 > python 从函数名看完整定义

问题描述

我最近问了一个标题为“python find the type of a function”的问题,得到了非常有用的答案。这是一个相关的问题。

假设我导入了我编写的 *.py 文件,这些导入导致f成为我定义的函数之一。现在我写信给我的 python 解释器x = f。稍后,我想查看 的完整定义f,最好还有注释,只知道x。这可能吗?python 是否记得定义是从哪个文件导入的,当然,这不足以给出 的完整定义f,除非可以找到实际的相关定义?

标签: pythonpython-3.xpython-import

解决方案


如果您为您评论过的某个函数加上别名,内置help(object)将为您提供正确的文档k- 相同inspect.getsource(k)- 他们知道k此时您的变量名称别名是哪个函数。

看:


例子:

# reusing this code - created it for some other question today

class well_documented_example_class(object):
    """Totally well documented class"""

    def parse(self, message):
        """This method does coool things with your 'message'

        'message' : a string with text in it to be parsed"""
        self.data = [x.strip() for x in message.split(' ')]
        return self.data


# alias for `parse()`:        
k = well_documented_example_class.parse
help(k)

印刷:

Help on function parse in module __main__:

parse(self, message)
    This method does coool things with your 'message'

    'message' : a string with text in it to be parsed

同样适用于inspect.getsource(k)

# from https://stackoverflow.com/a/52333691/7505395
import inspect
print(inspect.getsource(k))

印刷:

def parse(self, message):
    """This method does coool things with your 'message'

    'message' : a string with text in it to be parsed"""
    self.data = [x.strip() for x in message.split(' ')]
    return self.data

推荐阅读