英文:
What is the purpose of "if False:" here?
问题
Here is the translated content from the provided URL:
if False: # pragma: no cover (mypy)
from typing import Type
if sys.version_info >= (3,):
AsyncFunctionDef = ast.AsyncFunctionDef
else:
AsyncFunctionDef = ast.stmt
False
可以在 Python 2 中为真(可以被重新定义),但在 Python 3 中不能为真。这可能是一个笑话,或者是一个正在进行中的工作,或者是注释掉代码的方式,但这是一个相当成熟的工具,我是否漏掉了什么?
英文:
https://github.com/asottile/pyupgrade/blob/fecacc91e57c224a0bd2564579ef01238650126c/pyupgrade.py#L53
if False: # pragma: no cover (mypy)
from typing import Type
if sys.version_info >= (3,):
AsyncFunctionDef = ast.AsyncFunctionDef
else:
AsyncFunctionDef = ast.stmt
The commit is not revealing:
https://github.com/asottile/pyupgrade/commit/fecacc91e57c224a0bd2564579ef01238650126c#diff-8213eba6a28bcc759225cd8cf49b2fd1
False
can be truthy in Python 2 (where it can be re-defined) but not in Python 3. It might be a joke, or work in progress, or way of commenting out the code, but this is quite a mature tool- am I missing something?
答案1
得分: 5
AsyncFunctionDef
的值在运行时永远不需要,只在两个与 Python 2 兼容的类型提示(位于第 1298 和 1318 行)中被 mypy
使用。if False
阻止了在运行时发生赋值,但让 mypy
在类型检查期间看到正确的底层类型。(它还防止在 Python 2 中尝试导入 typing
模块时引发 ImportError
。)
在这里使用 typing.TYPE_CHECKING
会更清晰(其值在运行时为 False
,但在 mypy
运行时为 True
),但是要注意 typing.TYPE_CHECKING
在 Python 2 中同样不可用。
英文:
The value of AsyncFunctionDef
is never needed at runtime, only by mypy
in two Python-2-compatible type hints (at lines 1298 and 1318). The if False
prevents the assignments from occurring at run-time, but lets mypy
see the correct underlying type to use during type-checking. (It also prevents an ImportError
from being raised at the attempt to import the typing
module under Python 2.)
It would be clearer to use typing.TYPE_CHECKING
(whose value is False
at run-time, but True
when mypy
runs) here, except typing.TYPE_CHECKING
is also unavailable in Python 2.
答案2
得分: 5
if False
被用于if typing.TYPE_CHECKING
之上,因为python3.5.0-3.5.2受pyupgrade支持,不具有typing.TYPE_CHECKING
-- 你可以在flake8-typing-imports中找到更多信息(我也是这个flake8插件的作者)
在3.5.3+和typing
的后移版(在任何<3.5的版本中都可用)中,TYPE_CHECKING
可用
免责声明:我是pyupgrade的作者。
英文:
if False
is used over if typing.TYPE_CHECKING
because python3.5.0-3.5.2 is supported by pyupgrade and does not have typing.TYPE_CHECKING
-- you can find more information in flake8-typing-imports (I'm also the author of this flake8 plugin)
in 3.5.3+ and the typing
backport (available in anything <3.5) TYPE_CHECKING
is available
disclaimer: I'm the author of pyupgrade
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论