Python内省:在函数定义内访问函数名称和docstring [英] Python introspection: access function name and docstring inside function definition

查看:100
本文介绍了Python内省:在函数定义内访问函数名称和docstring的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下python代码:

Consider the following python code:

def function():
    "Docstring"

    name = ???
    doc = ???

    return name, doc

>>> function()
"function", "Docstring"

我需要用什么替换问号,以便从同一函数内部获取函数的名称和文档字符串?

What do I need to replace the question marks with so that I get the name and the docstring of the function from inside the same function?

到目前为止,大多数答案都在函数定义中明确地对函数名称进行了硬编码.可能会发生以下类似的情况,其中新函数get_name_doc从调用它的外部框架访问该函数,并返回其名称和doc?

Most of the answers so far explicitly hardcode the name of the function inside its definition. Is it possible do something like below where a new function get_name_doc would access the function from the outer frame from which it is called, and return its name and doc?

def get_name_doc():
    ???

def function():
    "Docstring"

    name, doc = get_name_doc()

    return name, doc

>>> function()
"function", "Docstring"

推荐答案

由于名称可以更改和重新分配,因此不可能以一致的方式进行整洁.

This is not possible to do cleanly in a consistent way because names can be changed and reassigned.

但是,只要不对函数进行重命名或修饰,就可以使用它.

However, you can use this so long as the function isn't renamed or decorated.

>>> def test():
...     """test"""
...     doc = test.__doc__
...     name = test.__name__
...     return doc, name
... 
>>> test()
('test', 'test')
>>> 

这根本不可靠.这是一个出错的例子.

It's not at all reliable. Here's an example of it going wrong.

>>> def dec(f):
...     def wrap():
...         """wrap"""
...         return f()
...     return wrap
... 
>>> @dec
... def test():
...     """test"""
...     return test.__name__, test.__doc__
... 
>>> test()
('wrap', 'wrap')
>>> 

这是因为名称test在实际创建函数时尚未定义,并且是函数中的全局引用.因此,每次执行都会在全局范围内对其进行查找.因此,在全局范围内更改名称(例如装饰器)将破坏您的代码.

This is because the name test isn't defined at the time that the function is actually created and is a global reference in the function. It hence gets looked up in the global scope on every execution. So changes to the name in the global scope (such as decorators) will break your code.

这篇关于Python内省:在函数定义内访问函数名称和docstring的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆