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

Partitions are not pickle-able #325

Closed
zschutzman opened this issue Oct 21, 2019 · 0 comments
Closed

Partitions are not pickle-able #325

zschutzman opened this issue Oct 21, 2019 · 0 comments

Comments

@zschutzman
Copy link
Contributor

zschutzman commented Oct 21, 2019

partition objects cannot be passed through the pickle serialization library. Below are more details and a fix. If we want to implement it, I can make a PR in the near future. If not, someone who really wants to pickle their partitions can look at this for guidance.


I tried to pickle a partition object and was met with

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "home/gerrychain/partition/partition.py", line 115, in __getattr__
    _k = self.__getitem__(key)
  File "/home/gerrychain/gerrychain/partition/partition.py", line 109, in __getitem__
    self._cache[key] = self.updaters[key](self)
KeyError: '__getstate__'

and while I don't understand the inner workings of the pickle library, I did manage to resolve the problem by redefining Partition.__getitem__ and Partition.__getattr__ to the following:

def __getitem__(self, key):
    """Allows accessing the values of updaters computed for this
    Partition instance.

    :param key: Property to access.
    """
    try:
        if key not in self._cache:
            self._cache[key] = self.updaters[key](self)
        return self._cache[key]
    except:
        return None

def __getattr__(self, key):
    _k = self.__getitem__(key)
    if _k == None:
        raise AttributeError
    return _k
This was referenced Feb 1, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants