繁体   English   中英

探测python函数

[英]Probing a python function

我可以在python中执行此操作,它为我提供了函数中可用的子模块/参数。

在解释器中,我可以这样做:

>>> from nltk import pos_tag
>>> dir(pos_tag)
['__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__doc__', '__format__', '__get__', '__getattribute__', '__globals__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name']

顺便说一句,什么是dir(function)调用?

我如何知道调用该函数所需的参数? 例如,在pos_tag的情况下,源代码说它需要token ,请参阅https://github.com/nltk/nltk/blob/develop/nltk/tag/ init .py

def pos_tag(tokens):
    """
    Use NLTK's currently recommended part of speech tagger to
    tag the given list of tokens.
        >>> from nltk.tag import pos_tag # doctest: +SKIP
        >>> from nltk.tokenize import word_tokenize # doctest: +SKIP
        >>> pos_tag(word_tokenize("John's big idea isn't all that bad.")) # doctest: +SKIP
        [('John', 'NNP'), ("'s", 'POS'), ('big', 'JJ'), ('idea', 'NN'), ('is',
        'VBZ'), ("n't", 'RB'), ('all', 'DT'), ('that', 'DT'), ('bad', 'JJ'),
        ('.', '.')]
    :param tokens: Sequence of tokens to be tagged
    :type tokens: list(str)
    :return: The tagged tokens
    :rtype: list(tuple(str, str))
    """
    tagger = load(_POS_TAGGER)
    return tagger.tag(tokens)

如果该函数有一个文档字符串,则有一种方法可以知道该函数对特定参数的期望参数类型是什么? ,例如,在上面的pos_tag情况下,它是:param tokens: Sequence of tokens to be tagged:type tokens: list(str)在运行解释器时无需阅读代码就能获得这些信息吗?

最后,是否有办法知道返回类型是什么?

只是要清楚一点,我不希望文档字符串打印出来,但是上面的问题是,这样我以后可以使用isinstance(output_object, type)某种类型检查。

以下是您四个问题的答案。 除非您想自己解析文档字符串,否则恐怕您在标准库中无法执行某些操作。

(1)顺便说一句,dir(function)叫什么?

如果我正确理解了这个问题,我相信文档会在这里回答该问题:

如果对象具有名为__dir__()方法,则将调用此方法,并且该方法必须返回属性列表。 这允许实现自定义__getattr__()__getattribute__()函数的对象自定义dir()报告其属性的方式。

如果对象不提供__dir__() ,则该函数将尽最大努力从该对象的__dict__属性(如果已定义)及其类型对象中收集信息。

(2)如何知道调用该函数所需的参数?

最好的方法是使用inspect

>>> from nltk import pos_tag
>>> from inspect import getargspec
>>> getargspec(pos_tag)
ArgSpec(args=['tokens'], varargs=None, keywords=None, defaults=None)  # a named tuple
>>> getargspec(pos_tag).args
['tokens']

(3)如果该函数有一个文档字符串,是否有办法知道该函数对特定参数的期望参数类型?

除非您想自己解析文档字符串,否则不在标准库中。 您可能已经知道可以像这样访问文档字符串:

>>> from inspect import getdoc
>>> print getdoc(pos_tag)
Use NLTK's currently recommended part of speech tagger to
tag the given list of tokens.

    >>> from nltk.tag import pos_tag
    >>> from nltk.tokenize import word_tokenize
    >>> pos_tag(word_tokenize("John's big idea isn't all that bad."))
    [('John', 'NNP'), ("'s", 'POS'), ('big', 'JJ'), ('idea', 'NN'), ('is',
    'VBZ'), ("n't", 'RB'), ('all', 'DT'), ('that', 'DT'), ('bad', 'JJ'),
    ('.', '.')]

:param tokens: Sequence of tokens to be tagged
:type tokens: list(str)
:return: The tagged tokens
:rtype: list(tuple(str, str))

或这个:

>>> print pos_tag.func_code.co_consts[0]

    Use NLTK's currently recommended part of speech tagger to
    tag the given list of tokens.

        >>> from nltk.tag import pos_tag
        >>> from nltk.tokenize import word_tokenize
        >>> pos_tag(word_tokenize("John's big idea isn't all that bad."))
        [('John', 'NNP'), ("'s", 'POS'), ('big', 'JJ'), ('idea', 'NN'), ('is',
        'VBZ'), ("n't", 'RB'), ('all', 'DT'), ('that', 'DT'), ('bad', 'JJ'),
        ('.', '.')]

    :param tokens: Sequence of tokens to be tagged
    :type tokens: list(str)
    :return: The tagged tokens
    :rtype: list(tuple(str, str))

如果要尝试自己解析参数和“类型”,则可以从正则表达式开始。 显然,尽管如此,我松散地使用了“类型”一词。 此外,此方法仅适用于以这种特定方式列出其参数和类型的文档字符串:

>>> import re
>>> params = re.findall(r'(?<=:)type\s+([\w]+):\s*(.*?)(?=\n|$)', getdoc(pos_tag))
>>> for param, type_ in params:
    print param, '=>', type_

tokens => list(str)

当然,这种方法的结果将为您提供参数及其相应的描述。 您还可以通过拆分字符串并仅保留符合以下要求的单词来检查描述中的每个单词:

>>> isinstance(eval(word), type)
True
>>> isinstance(eval('list'), type)
True

但是这种方法可能很快变得复杂,尤其是在尝试解析pos_tag的最后一个参数时。 此外,文档字符串通常通常根本没有这种格式。 因此,这可能仅适用于nltk ,但即使nltk ,也并非始终如此。

(4)最后,有没有办法知道什么是返回类型?

同样,除非您想使用上面的正则表达式示例来梳理文档字符串,否则恐怕不会。 返回类型可能会根据arg类型的不同而有所不同。 (考虑任何可与任何可迭代对象一起使用的函数。)如果您想尝试从文档字符串中提取此信息(再次以pos_tag文档字符串的确切格式),则可以尝试另一个正则表达式:

>>> return_ = re.search(r'(?<=:)rtype:\s*(.*?)(?=\n|$)', getdoc(pos_tag))
>>> if return_:
    print 'return "type" =', return_.group()

return "type" = rtype: list(tuple(str, str))

否则,我们在这里能做的最好的事情就是获取源代码(同样,这显然是您不想要的):

>>> import inspect
>>> print inspect.getsource(pos_tag)
def pos_tag(tokens):
    """
    Use NLTK's currently recommended part of speech tagger to
    tag the given list of tokens.

        >>> from nltk.tag import pos_tag
        >>> from nltk.tokenize import word_tokenize
        >>> pos_tag(word_tokenize("John's big idea isn't all that bad."))
        [('John', 'NNP'), ("'s", 'POS'), ('big', 'JJ'), ('idea', 'NN'), ('is',
        'VBZ'), ("n't", 'RB'), ('all', 'DT'), ('that', 'DT'), ('bad', 'JJ'),
        ('.', '.')]

    :param tokens: Sequence of tokens to be tagged
    :type tokens: list(str)
    :return: The tagged tokens
    :rtype: list(tuple(str, str))
    """
    tagger = load(_POS_TAGGER)
    return tagger.tag(tokens)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM