### Install perflint Python Linter Source: https://github.com/tonybaloney/perflint/blob/main/README.md This snippet demonstrates how to install the perflint linter using pip. Perflint is a Python package available on PyPI, making installation straightforward. ```console pip install perflint ``` -------------------------------- ### Configure VS Code for perflint with Pylint Source: https://github.com/tonybaloney/perflint/blob/main/README.md This JSON configuration snippet shows how to integrate perflint into VS Code's Python linting setup. It enables Pylint, ensures perflint is loaded as a plugin, and specifies a custom Pylint configuration file for project-specific settings. ```javascript { "python.linting.pylintEnabled": true, "python.linting.enabled": true, "python.linting.pylintArgs": [ "--load-plugins", "perflint", "--rcfile", "${workspaceFolder}/.pylintrc" ] } ``` -------------------------------- ### Optimize Loop Invariant Statements (W8201) - Corrected Example Source: https://github.com/tonybaloney/perflint/blob/main/README.md This snippet provides the optimized version for the `loop-invariant-statement` rule. By pre-calculating `len(x)` outside the loop and storing it in a variable `n`, the `n * i` expression becomes more efficient, demonstrating the recommended practice. ```python def loop_invariant_statement(): """Catch basic loop-invariant function call.""" x = (1,2,3,4) n = len(x) for i in range(10_000): print(n * i) # [loop-invariant-statement] ``` -------------------------------- ### Python: Constructing Dictionaries with For-Loops (to be refactored) Source: https://github.com/tonybaloney/perflint/blob/main/README.md This Python code demonstrates two scenarios where a dictionary is constructed using a traditional for-loop. The first function shows a basic construction, and the second includes a conditional filter. These examples are provided to illustrate cases where a dictionary comprehension would be a more idiomatic and efficient alternative. ```python def should_be_a_dict_comprehension(): pairs = (("a", 1), ("b", 2)) result = {} for x, y in pairs: result[x] = y def should_be_a_dict_comprehension_filtered(): pairs = (("a", 1), ("b", 2)) result = {} for x, y in pairs: if y % 2: result[x] = y ``` -------------------------------- ### Flag Loop Invariant Statements (W8201) - Basic Example Source: https://github.com/tonybaloney/perflint/blob/main/README.md This rule detects expressions within a loop whose result remains constant across iterations. Evaluating such expressions outside the loop improves performance by avoiding redundant computations. The example shows `len(x)` being unnecessarily calculated inside the loop. ```python def loop_invariant_statement(): """Catch basic loop-invariant function call.""" x = (1,2,3,4) for i in range(10_000): # x is never changed in this loop scope, # so this expression should be evaluated outside print(len(x) * i) # [loop-invariant-statement] # ^^^^^^ ``` -------------------------------- ### Identify Complex Loop Invariant Expressions (W8201) Source: https://github.com/tonybaloney/perflint/blob/main/README.md This example illustrates how the loop-invariance checker identifies sub-expressions that are constant within a loop. Even parts of a larger expression, like `len(x) * i`, can be flagged if they don't change per iteration, indicating potential for optimization. ```python def loop_invariant_statement_more_complex(): """Catch basic loop-invariant function call.""" x = [1,2,3,4] i = 6 for j in range(10_000): # x is never changed in this loop scope, # so this expression should be evaluated outside print(len(x) * i + j) # ^^^^^^^^^^ [loop-invariant-statement] ``` -------------------------------- ### Optimize Python Global Variable Access in Loops Source: https://github.com/tonybaloney/perflint/blob/main/README.md This example illustrates how accessing global variables directly within a loop can be less efficient than copying their values to local 'fast' variables before the loop. Copying values to locals can lead to significant speed improvements (e.g., 65% faster) for repeated access. ```python d = { "x": 1234, "y": 5678, } def dont_copy_dict_key_to_fast(): for _ in range(100000): d["x"] + d["y"] d["x"] + d["y"] d["x"] + d["y"] d["x"] + d["y"] d["x"] + d["y"] def copy_dict_key_to_fast(): i = d["x"] j = d["y"] for _ in range(100000): i + j i + j i + j i + j i + j ``` -------------------------------- ### Handle Loop Invariant Statements with Method Side Effects (W8201) Source: https://github.com/tonybaloney/perflint/blob/main/README.md This example demonstrates that methods called on a variable are assumed to have side effects, preventing them from being marked as loop-invariant. Even if `len(x) * i` appears invariant, `x.clear()` modifies `x`, invalidating the assumption and preventing the rule from flagging it. ```python def loop_invariant_statement_method_side_effect(): """Catch basic loop-invariant function call.""" x = [1,2,3,4] i = 6 for j in range(10_000): print(len(x) * i + j) x.clear() # x changes as a side-effect ``` -------------------------------- ### Identify Unnecessary List Casts (W8101) Source: https://github.com/tonybaloney/perflint/blob/main/README.md This rule flags inefficient use of `list()` on an already iterable type, such as a tuple. Casting creates an unnecessary second iterator, impacting performance. The example demonstrates a tuple being cast to a list within a loop, which perflint identifies as an anti-pattern. ```python def simple_static_tuple(): """Test warning for casting a tuple to a list.""" items = (1, 2, 3) for i in list(items): # [unnecessary-list-cast] print(i) ``` -------------------------------- ### Detect Incorrect Dictionary Iteration (W8102) Source: https://github.com/tonybaloney/perflint/blob/main/README.md This rule identifies inefficient dictionary iteration when keys or values are discarded using `_` with `.items()`. It recommends using `.keys()` or `.values()` directly for better performance, as dictionaries store keys and values separately. The example shows common scenarios where this rule would apply. ```python def simple_dict_keys(): """Check that dictionary .items() is being used correctly. """ fruit = { 'a': 'Apple', 'b': 'Banana', } for _, value in fruit.items(): # [incorrect-dictionary-iterator] print(value) for key, _ in fruit.items(): # [incorrect-dictionary-iterator] print(key) ``` -------------------------------- ### Run perflint as a Standalone Linter Source: https://github.com/tonybaloney/perflint/blob/main/README.md This snippet shows how to use perflint directly from the command line to lint a specified directory or file. It performs a standalone analysis of your Python code for performance anti-patterns. ```console perflint your_code/ ``` -------------------------------- ### Integrate perflint as a Pylint Plugin Source: https://github.com/tonybaloney/perflint/blob/main/README.md This snippet illustrates how to load perflint as a plugin within Pylint. This allows perflint's performance checks to be run alongside Pylint's standard linting process, extending its capabilities. ```console pylint your_code/ --load-plugins=perflint ``` -------------------------------- ### Optimize Python Dotted Imports in Loops Source: https://github.com/tonybaloney/perflint/blob/main/README.md This snippet demonstrates the performance difference between using dotted imports (e.g., os.path.exists) and direct imports (e.g., from os.path import exists) within a loop. Direct imports are shown to be 10-15% faster as they avoid repeated attribute lookups. ```python from os.path import exists import os def dotted_import(): for _ in range(100_000): return os.path.exists('/') def direct_import(): for _ in range(100_000): return exists('/') ``` -------------------------------- ### Use Python List Copy Methods for List Duplication Source: https://github.com/tonybaloney/perflint/blob/main/README.md This snippet recommends using built-in methods like list() constructor or list.copy() for duplicating lists instead of manually iterating and appending in a for loop. These methods are more efficient for creating a copy. ```python def should_be_a_list_copy(): """Using the copy() method would be more efficient.""" original = range(10_000) filtered = [] for i in original: filtered.append(i) ``` ```python def better_list_copy(): original = range(10_000) filtered = list(original) # or original.copy() ``` -------------------------------- ### Optimize Python Dotted Imports for Global Attributes in Loops Source: https://github.com/tonybaloney/perflint/blob/main/README.md This section reiterates the inefficiency of accessing module attributes (like os.environ or os.path.exists) within a loop. It explains that such access involves multiple slow lookups per iteration and suggests importing the specific name directly (e.g., from os import environ) for a 10-15% performance gain. ```python import os # NOQA def test_dotted_import(items): for item in items: val = os.environ[item] # Use `from os import environ` def even_worse_dotted_import(items): for item in items: val = os.path.exists(item) # Use `from os.path import exists` instead ``` -------------------------------- ### Use Python List Comprehensions for List Creation Source: https://github.com/tonybaloney/perflint/blob/main/README.md This section highlights that list comprehensions are significantly more efficient (around 25% faster) than traditional for loops for creating new lists, even when filtering conditions are involved. ```python def should_be_a_list_comprehension_filtered(): """A List comprehension would be more efficient.""" original = range(10_000) filtered = [] for i in original: if i % 2: filtered.append(i) ``` ```python def better_list_comprehension_filtered(): original = range(10_000) filtered = [i for i in original if i % 2] ``` -------------------------------- ### Prefer Python Tuples for Non-Mutated Sequences Source: https://github.com/tonybaloney/perflint/blob/main/README.md This snippet advises using tuples instead of lists when a sequence is not intended to be mutated. Tuples are faster to construct and index compared to lists, offering performance benefits for immutable data structures. ```python def index_mutated_list(): fruit = ["banana", "pear", "orange"] fruit[2] = "mandarin" len(fruit) for i in fruit: print(i) def index_non_mutated_list(): fruit = ["banana", "pear", "orange"] # Raises [use-tuple-over-list] print(fruit[2]) len(fruit) for i in fruit: print(i) ``` -------------------------------- ### Optimize Python Bytes Slicing with Memoryview Source: https://github.com/tonybaloney/perflint/blob/main/README.md This snippet explains that slicing bytes objects in a loop is inefficient because it creates copies of data. It recommends using memoryview for zero-copy interactions, which can make operations 30-40% faster. ```python def bytes_slice(): """Slice using normal bytes""" word = b'A' * 1000 for i in range(1000): n = word[0:i] # ^^^^^^^^^ memoryview-over-bytes def memoryview_slice(): """Convert to a memoryview first.""" word = memoryview(b'A' * 1000) for i in range(1000): n = word[0:i] ``` -------------------------------- ### Avoid Python Try-Except Blocks Inside Loops Source: https://github.com/tonybaloney/perflint/blob/main/README.md This section advises against placing try...except blocks directly inside loops due to their significant computational overhead, especially in Python versions up to 3.10. It recommends refactoring code to move the entire loop into a single try block to improve performance. ```python # Inefficient: Try-except inside loop def inefficient_try_except_loop(): for i in range(1000): try: # some operation result = 1 / i except ZeroDivisionError: result = 0 # Efficient: Try-except outside loop def efficient_try_except_loop(): try: for i in range(1000): # some operation result = 1 / i except ZeroDivisionError: # handle error for the entire loop or specific cases pass ``` -------------------------------- ### Detect Loop Invariant Branches (W8201) Source: https://github.com/tonybaloney/perflint/blob/main/README.md This rule extends loop-invariance detection to entire conditional branches. If an expression controlling a branch, or expressions within it, are invariant, the entire branch can be marked for extraction outside the loop, as shown with `len(x) > 2` and `x * i`. ```python def loop_invariant_branching(): """Ensure node is walked up to find a loop-invariant branch""" x = [1,2,3,4] i = 6 for j in range(10_000): # Marks entire branch if len(x) > 2: print(x * i) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.