asottile / pyupgrade

A tool (and pre-commit hook) to automatically upgrade syntax for newer versions of the language.
MIT License
3.5k stars 177 forks source link

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

Open EwoutH opened 10 months ago

EwoutH commented 10 months ago

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"))
asottile commented 10 months ago

I've never seen someone write that

EwoutH commented 10 months ago

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

hugovk commented 10 months ago

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

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

jond01 commented 7 months ago

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