Skip to content

Instantly share code, notes, and snippets.

@Winand
Last active April 3, 2024 14:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Winand/992f99fb4ff1186e6fdccd23aff6de0c to your computer and use it in GitHub Desktop.
Save Winand/992f99fb4ff1186e6fdccd23aff6de0c to your computer and use it in GitHub Desktop.
Lazy conversion of dictionary to JSON string
import json
import logging
import time
logger = logging.getLogger()
d = {"A": 1, "B": 2, "C": {'a': 'hello', "_": 'world'}}
class LazyDictStr:
"Converts dictionary to formatted JSON string when str(...) called"
def __init__(self, dictionary: dict):
self.dictionary = dictionary
def __str__(self):
return json.dumps(self.dictionary, indent=2)
logger.warning("This is a dictionary:\n%s", LazyDictStr(d)) # dict is converted
logger.debug("This is a dictionary:\n%s", LazyDictStr(d)) # dict is NOT converted
a = time.perf_counter()
for i in range(100000):
j = LazyDictStr(d)
print("No conversion", time.perf_counter() - a)
a = time.perf_counter()
for i in range(100000):
j = json.dumps(d, indent=2)
print("Direct conversion", time.perf_counter() - a)
a = time.perf_counter()
for i in range(100000):
j = str(LazyDictStr(d))
print("Lazy conversion", time.perf_counter() - a)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment