From fb504931275a7ac99d6855f0225ad2496c2c293c Mon Sep 17 00:00:00 2001 From: Flavio Curella <89607+fcurella@users.noreply.github.com> Date: Mon, 12 Jul 2021 09:17:26 -0500 Subject: [PATCH] enable faker instances to be unpickled (#1480) --- faker/proxy.py | 13 +++++++++++++ tests/test_proxy.py | 6 ++++++ 2 files changed, 19 insertions(+) diff --git a/faker/proxy.py b/faker/proxy.py index 4fd7f220e9..25d29525d1 100644 --- a/faker/proxy.py +++ b/faker/proxy.py @@ -127,6 +127,9 @@ def __deepcopy__(self, memodict={}): } return result + def __setstate__(self, state): + self.__dict__.update(state) + @property def unique(self): return self._unique_proxy @@ -280,6 +283,16 @@ def __getattr__(self, name: str): else: raise TypeError("Accessing non-functions through .unique is not supported.") + def __getstate__(self): + # Copy the object's state from self.__dict__ which contains + # all our instance attributes. Always use the dict.copy() + # method to avoid modifying the original state. + state = self.__dict__.copy() + return state + + def __setstate__(self, state): + self.__dict__.update(state) + def _wrap(self, name, function): @functools.wraps(function) def wrapper(*args, **kwargs): diff --git a/tests/test_proxy.py b/tests/test_proxy.py index a72718822b..f2cacd5328 100644 --- a/tests/test_proxy.py +++ b/tests/test_proxy.py @@ -1,4 +1,5 @@ import copy +import pickle import random from collections import OrderedDict @@ -396,3 +397,8 @@ def test_copy(self): fake2 = copy.deepcopy(fake) assert fake.locales == fake2.locales assert fake.locales is not fake2.locales + + def test_pickle(self): + fake = Faker() + pickled = pickle.dumps(fake) + pickle.loads(pickled)