gpt4 book ai didi

python - 由于旧的解释器版本,如何优雅地处理失败的 future 功能(__future__)导入?

转载 作者:IT老高 更新时间:2023-10-28 21:37:37 25 4
gpt4 key购买 nike

您如何优雅地处理失败的 future 功能导入?如果用户使用 Python 2.5 运行并且我的模块中的第一条语句是:

from __future__ import print_function

为 Python 2.5 编译此模块将失败并显示:

  File "__init__.py", line 1
from __future__ import print_function
SyntaxError: future feature print_function is not defined

我想通知用户他们需要使用 Python >= 2.6 重新运行程序,并且可能会提供一些有关如何执行此操作的说明。但是,引用 PEP 236 :

The only lines that can appear before a future_statement are:

  • The module docstring (if any).
  • Comments.
  • Blank lines.
  • Other future_statements.

所以我不能这样做:

import __future__

if hasattr(__future__, 'print_function'):
from __future__ import print_function
else:
raise ImportError('Python >= 2.6 is required')

因为它产生:

  File "__init__.py", line 4
from __future__ import print_function
SyntaxError: from __future__ imports must occur at the beginning of the file

PEP 中的这个片段似乎给了内联执行它的希望:

Q: I want to wrap future_statements in try/except blocks, so I can use different code depending on which version of Python I'm running. Why can't I?

A: Sorry! try/except is a runtime feature; future_statements are primarily compile-time gimmicks, and your try/except happens long after the compiler is done. That is, by the time you do try/except, the semantics in effect for the module are already a done deal. Since the try/except wouldn't accomplish what it looks like it should accomplish, it's simply not allowed. We also want to keep these special statements very easy to find and to recognize.

Note that you can import __future__ directly, and use the information in it, along with sys.version_info, to figure out where the release you're running under stands in relation to a given feature's status.

想法?

最佳答案

“我想通知用户他们需要使用 Python >= 2.6 重新运行程序,并且可能会提供一些有关如何执行此操作的说明。”

这不就是 README 文件的用途吗?

这是您的选择。 “包装器”:在运行目标 aop 之前检查环境的一小段 Python。

文件:appwrapper.py

import sys
major, minor, micro, releaselevel, serial = sys.version_info
if (major,minor) <= (2,5):
# provide advice on getting version 2.6 or higher.
sys.exit(2)
import app
app.main()

什么是“直接导入”。您可以检查 __future__ 的内容。您仍然受制于 a from __future__ import print_function 是编译器的信息这一事实,但您可以在导入执行实际工作的模块之前四处寻找。

import __future__, sys
if hasattr(__future__, 'print_function'):
# Could also check sys.version_info >= __future__. print_function.optional
import app
app.main()
else:
print "instructions for upgrading"

关于python - 由于旧的解释器版本,如何优雅地处理失败的 future 功能(__future__)导入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/388069/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com