pythoncapi中的PyCompilerFlags是什么?

2024-09-30 01:20:08 发布

您现在位置:Python中文网/ 问答频道 /正文

如果您检查了Python C-API documentation关于通过C调用运行Python代码的信息,您会发现总是提到PyCompilerFlags,但是除了文档的最后一部分之外,没有真正描述它是什么,也没有提到它的可能值及其对执行的影响。在


Tags: 代码文档api信息documentationpycompilerflags
1条回答
网友
1楼 · 发布于 2024-09-30 01:20:08

PyCompilerFlags是等效于传递给compile和相关函数的flags参数的C API。如果在查看cpythonc-API文档之前还不知道Python文档的前后关系,那么这一点可能就不明显了。在

来自^{}

The optional arguments flags and dont_inherit control which future statements affect the compilation of source. If neither is present (or both are zero) the code is compiled with those future statements that are in effect in the code that is calling compile(). If the flags argument is given and dont_inherit is not (or is zero) then the future statements specified by the flags argument are used in addition to those that would be used anyway. If dont_inherit is a non-zero integer then the flags argument is it – the future statements in effect around the call to compile are ignored.

Future statements are specified by bits which can be bitwise ORed together to specify multiple statements. The bitfield required to specify a given feature can be found as the compiler_flag attribute on the _Feature instance in the __future__ module.

在指向future statements的链接后面提供了有关它们如何工作的详细信息,^{}的链接有一个图表,显示了可用的未来语句列表。在


另一件可能不明显的事情:每个future特性标志对应于一个code对象的co_flags属性中的一个标志。所以:

code = compile('1 <> 2', '', 'eval', flags=__future__.barry_as_FLUFL.compiler_flag)
assert code.co_flags & CO_FUTURE_BARRY_AS_BDFL

在C语言中,如果传递struct PyCompilerFlags flags = { CO_FUTURE_BARRY_AS_BDFL }以获得相同的效果。在

如果要查看这些标志的实际数值,必须在C源代码或^{}源中查找相应的^{}常量。在


在一些方面,C API中的情况略有不同。在

  • 不是同时传递标志dont\u inherit,而是只传递标志,它是您希望在PyRun_*PyCompile_*调用期间生效的所有未来语句的完整集合。在
  • 大多数函数都使用一个PyCompile_Flags结构来保存int,而不是原始int。这只是为了进行类型检查;在内存中,保存int的结构的存储方式与int相同
  • 许多函数通过指针获取其标志,因此您可以在运行代码后检索可能更新的标志集。在

让我们看一个完整的例子。我将使用Python2.7,尽管我已经链接到了3.7文档,只是因为使用print的示例比使用forward注释的示例简单。在

此代码打印空元组:

^{pr2}$

但是如果使用PyRun_SimpleStringFlags运行第一个,并将CO_FUTURE_PRINT_FUNCTION(0x10000)作为标志`,它将打印一个空白行,即lapython3。在

如果运行此代码:

^{3}$

…那么无论您传入0还是CO_FUTURE_PRINT_FUNCTION,它都将打印一个空白行。在调用之后,如果您查看通过引用传递的标志,它将具有CO_FUTURE_PRINT_FUNCTION或d。因此,如果您一次编译和运行一个块,您可以将相同的值传递给下一个字符串,它将继承该future标志。(就像在交互式解释器中编写future语句一样,它会影响之后解释的所有语句。)

相关问题 更多 >

    热门问题