Skip to content

Commit

Permalink
enable faker instances to be unpickled (#1480)
Browse files Browse the repository at this point in the history
  • Loading branch information
fcurella authored Jul 12, 2021
1 parent 6264427 commit fb50493
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
13 changes: 13 additions & 0 deletions faker/proxy.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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):
Expand Down
6 changes: 6 additions & 0 deletions tests/test_proxy.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import copy
import pickle
import random

from collections import OrderedDict
Expand Down Expand Up @@ -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)

0 comments on commit fb50493

Please sign in to comment.