Skip to content

Commit 0cf9c7b

Browse files
Use a cache for compiled jinja templates (#913)
* Add a bytecode cache to speed up jinja template compilation * Honor TMPDIR env variable if it is set Co-authored-by: Andre Sailer <[email protected]> --------- Co-authored-by: Juan Miguel Carceller <[email protected]> Co-authored-by: Andre Sailer <[email protected]>
1 parent cdbac1b commit 0cf9c7b

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

python/podio_gen/generator_base.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,24 @@
1515
THIS_DIR = os.path.dirname(os.path.abspath(__file__))
1616
PYTHONBASE_DIR = os.path.abspath(THIS_DIR + "/../")
1717
TEMPLATE_DIR = os.path.join(PYTHONBASE_DIR, "templates")
18+
CACHE_DIR = os.path.join(os.environ.get("TMPDIR", "/tmp"), "podio", "jinja2_cache")
19+
20+
21+
def _get_bytecode_cache():
22+
"""Get a bytecode cache for Jinja2 templates.
23+
24+
Uses a file-based cache in a cache directory.
25+
This persists compiled templates across Python processes, providing
26+
significant speedup for subsequent code generation runs.
27+
"""
28+
29+
try:
30+
os.makedirs(CACHE_DIR, exist_ok=True)
31+
return jinja2.FileSystemBytecodeCache(CACHE_DIR)
32+
except OSError:
33+
# Fall back to no caching if we can't create the directory
34+
print(f"Warning: Could not create cache directory {CACHE_DIR}. ")
35+
return None
1836

1937

2038
def write_file_if_changed(filename, content, force_write=False):
@@ -142,6 +160,7 @@ def __init__(
142160
keep_trailing_newline=True,
143161
lstrip_blocks=True,
144162
trim_blocks=True,
163+
bytecode_cache=_get_bytecode_cache(),
145164
)
146165

147166
self.get_syntax = self.datamodel.options["getSyntax"]

0 commit comments

Comments
 (0)