tonybaloney / perflint

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

Add rule to check for eager log message string formatting #53

Open naglis opened 8 months ago

naglis commented 8 months ago

Log message string formatting should be delegated to the logging framework. This way the string formatting will not be performed if the particular logging level is not enabled.

import logging
import time

class Foo:
    def __init__(self, value: int):
        self.value = value

    def __str__(self):
        print(f"Calling Foo expensive __str__ on Foo with value {self.value}")
        time.sleep(0.25)
        return f"My value is: {self.value}"

def eager_formatting():
    foo = Foo(1)
    # Expensive Foo.__str__ will be called even though logging.DEBUG level is not enabled.
    logging.debug("The value of `foo` is %s" % foo)

def lazy_formatting():
    foo = Foo(1)
    # Expensive Foo.__str__ will not be called since logging.DEBUG level is not enabled.
    logging.debug("The value of `foo` is %s", foo)