Chris_Rands
Chris_Rands

Reputation: 41168

What is the purpose of "if False:" here?

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?

Upvotes: 2

Views: 1010

Answers (2)

anthony sottile
anthony sottile

Reputation: 69944

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

Upvotes: 5

chepner
chepner

Reputation: 531235

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.

Upvotes: 5

Related Questions