pyupgrade icon indicating copy to clipboard operation
pyupgrade copied to clipboard

Recognize and replace `if sys.version_info[0]` blocks

Open EwoutH opened this issue 2 years ago • 4 comments

pyupgrade currently does detect the if sys.version_info < (3, 5): syntax, it doesn't recognize the lesser but still sometimes used if sys.version_info[0] < 3: syntax in if or if-else blocks. It would be a nice feature if pyupgrade also could recognize and automatically replace such blocks.

A few examples I encountered in the wild:

if sys.version_info[0] < 3:
    import shutil
    shutil.rmtree(cls._tmpdir)
else:
    cls._tmpdir.cleanup()
if (sys.version_info[0] >=3 and
        isinstance(node, StringNode) and
        node.unicode_value is not None):
    return (node.unicode_value, node.pos)
return (node.compile_time_value(empty_scope), node.pos)
if sys.version_info[0] != 2:
    self.assertTrue(StringEncoding.string_contains_lone_surrogates("\uD800\uDFFF"))

EwoutH avatar Nov 16 '23 10:11 EwoutH

I've never seen someone write that

asottile avatar Nov 16 '23 13:11 asottile

For some reason Cython is full of it: cython/cython#5828/files (don't ask me why)

EwoutH avatar Nov 16 '23 13:11 EwoutH

There's a lot of it out there: tensorflow, protobuf, opencv, pytorch...

  • https://github.com/search?q=sys.version_info%5B0%5D&ref=opensearch&type=code
  • https://grep.app/search?q=sys.version_info%5B0%5D

And it's in the CPython 2-to-3 porting guide:

  • https://docs.python.org/3/howto/pyporting.html

hugovk avatar Nov 16 '23 15:11 hugovk

+1 for this feature request. Some more examples: https://github.com/mlrun/mlrun/pull/4796/commits/b8bf28191c64559252f03e6ffd50581fda541346

jond01 avatar Feb 06 '24 14:02 jond01