Skip to content

Commit 2c11274

Browse files
authored
Make Element class pickleable (#99)
* Make Element class pickleable Make Element class pickleable by stripping the ._env attribute when pickling and re-adding it when unpickling * Add type hinting, improve clarity
1 parent 2caa26d commit 2c11274

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed

branca/element.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,21 @@ def __init__(self, template=None, template_name=None):
6262
elif template_name is not None:
6363
self._template = ENV.get_template(template_name)
6464

65+
def __getstate__(self):
66+
"""Modify object state when pickling the object.
67+
jinja2 Environment cannot be pickled, so set
68+
the ._env attribute to None. This will be added back
69+
when unpickling (see __setstate__)
70+
"""
71+
state: dict = self.__dict__.copy()
72+
state["_env"] = None
73+
return state
74+
75+
def __setstate__(self, state: dict):
76+
"""Re-add ._env attribute when unpickling"""
77+
state["_env"] = ENV
78+
self.__dict__.update(state)
79+
6580
def get_name(self):
6681
"""Returns a string representation of the object.
6782
This string has to be unique and to be a python and

0 commit comments

Comments
 (0)