tonybaloney / perflint

Python Linter for performance anti patterns
MIT License
659 stars 10 forks source link

Incorrect loop-invariant-global-usage warnings #26

Closed pR0Ps closed 2 years ago

pR0Ps commented 2 years ago

Given the following code snippet:

x = 5
for y in range(10):
    print(x)
    print(y)

The variable x is already hoisted out of the loop and y cannot be since it depends on the range() iterator. Running perflint over the code gives loop-invariant-global-usage warnings for both variables:

$ perflint repro.py
************* Module repro
repro.py:3:10: W8202: Lookups of global names within a loop is inefficient, copy to a local variable outside of the loop first. (loop-invariant-global-usage)
repro.py:4:10: W8202: Lookups of global names within a loop is inefficient, copy to a local variable outside of the loop first. (loop-invariant-global-usage)

This is using perflint at commit 388d2736:

$ perflint --version
pylint 2.13.7
astroid 2.11.3
Python 3.10.4 (main, Mar 29 2022, 23:31:50) [Clang 10.0.1 (clang-1001.0.46.4)]
tonybaloney commented 2 years ago

The warning is badly named. It's complaining because you're using global names in a loop (not because they're invariant).

Because the code is a module, it's accurate to report those as globals. (Check the byte code)