pyupgrade
pyupgrade copied to clipboard
Recognize and replace `if sys.version_info[0]` blocks
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"))
I've never seen someone write that
For some reason Cython is full of it: cython/cython#5828/files (don't ask me why)
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
+1 for this feature request. Some more examples: https://github.com/mlrun/mlrun/pull/4796/commits/b8bf28191c64559252f03e6ffd50581fda541346