Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

enable faker instances to be unpickled #1480

Merged
merged 1 commit into from
Jul 12, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)