Skip to content

Instantly share code, notes, and snippets.

@tbrlpld
Last active April 15, 2020 17:13
Show Gist options
  • Select an option

  • Save tbrlpld/551e52324380e937dde0e8a4e9cfdc7e to your computer and use it in GitHub Desktop.

Select an option

Save tbrlpld/551e52324380e937dde0e8a4e9cfdc7e to your computer and use it in GitHub Desktop.
Avoid function execution for not logged messages
import logging
logger = logging.getLogger(__name__)
# Log level is INFO. So anything of lower level (DEBUG) should not execute
logger.setLevel(logging.INFO)
stream_handler = logging.StreamHandler()
logger.addHandler(stream_handler)
urls = ("a", "c", "b", "a")
def sort_urls(urls):
print("Sorting urls")
return sorted(urls)
class LazySortedURLs(object):
def __init__(self, urls):
print("Instanciating")
self.urls = urls
def __str__(self):
print("Sorting urls")
return str(sorted(urls))
# The debug message is not logged, but the sorting is still executed.
# This may be unimportant for small collections, but is can become very costly is the collection is large.
logger.debug("Debug sorted urls: %s", sort_urls(urls))
logger.info("Info sorted urls: %s", sort_urls(urls))
# When using a custom class to wrap the sorting, it looks like the `__str__`
# method is only evaluated when it is needed ("lazy"). The object is
# instanciated but not printed.
logger.debug("Debug lazy sorted urls: %s", LazySortedURLs(urls))
logger.info("Info lazy sorted urls: %s", LazySortedURLs(urls))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment