__signature__ 和 __text_signature__ 在 Python 3.4 中的用途是什么 [英] What are __signature__ and __text_signature__ used for in Python 3.4

查看:57
本文介绍了__signature__ 和 __text_signature__ 在 Python 3.4 中的用途是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果对 CPython 3.4 上的某些内置可调用对象(类构造函数、方法等)执行 dir(),您会发现其中许多通常具有称为 __text_signature__<的特殊属性/code>,例如:

<预><代码>>>>object.__text_signature__'()'>>>int.__text_signature__>>># 没有

然而,这方面的文档并不存在.此外,谷歌搜索属性名称表明还有另一个可能的特殊属性 __signature__,尽管我没有找到任何内置函数.

我确实知道它们与函数参数签名有关,但除此之外别无他法,它们的值表示什么以及它们的用途是什么?

解决方案

这些属性用于启用对 C 代码中定义的 Python 对象的内省.C-API Argument Clinic 提供数据,以协助 构建时检查模块签名 对象.之前不支持 C-API 函数的内省.

见内部() 函数关于如何使用 __text_signature__ 值.

目前,__text_signature__ 属性是从 C-API 中对象上设置的内部文档字符串填充的;对 objectname(...)\n--\n\n 进行了简单的文本搜索,其中 \n--\n\n 是典型的 Attribute诊所生成的文档字符串.看看type> 对象槽 如果你想找到一些例子.或者您可以查看 audioop 模块源 查看如何使用 Argument Clinic 定义签名;参数诊所脚本在构建时运行生成文档字符串(在随附的 audioop. 文件).

__signature__ 属性,如果存在,将是一个 inspect.Signature() 对象;C-API 可以提供完全解析的 Signature 实例,而不是提供文本版本.

If one does dir() on some builtin callables (class constructors, methods, etc) on CPython 3.4, one finds out that many of them often have a special attribute called __text_signature__, for example:

>>> object.__text_signature__
'()'
>>> int.__text_signature__
>>> # was None

However the documentation for this is nonexistent. Furthermore, googling for the attribute name suggests that there is also another possible special attribute __signature__, though I did not find any built-in functions that would have it.

I do know they are related to the function argument signature, but nothing beyond that, what do their values signify and what is the use of them?

解决方案

These attributes are there to enable introspection for Python objects defined in C code. The C-API Argument Clinic provides the data, to assist the inspect module when building Signature objects. Introspection of C-API functions was not supported before.

See the internal inspect._signature_fromstr() function on how the __text_signature__ value is used.

Currently, the __text_signature__ attribute is filled from the internal docstring set on objects in the C-API; a simple text search is done for objectname(...)\n--\n\n, where the \n--\n\n is typical of Attribute Clinic-generated documentation strings. Take a look at the type object slots if you wanted to find some examples. Or you could look at the audioop module source to see how the Argument Clinic is being used to define signatures; the Argument Clinic script is run on those when building to generate the docstrings (in the accompanying audioop.c.h file).

The __signature__ attribute, if present, would be a inspect.Signature() object; instead of providing a text version a C-API can provide a fully parsed Signature instance instead.

这篇关于__signature__ 和 __text_signature__ 在 Python 3.4 中的用途是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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