Last active
April 3, 2024 14:11
-
-
Save Winand/992f99fb4ff1186e6fdccd23aff6de0c to your computer and use it in GitHub Desktop.
Lazy conversion of dictionary to JSON string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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