Wrzlprmft
Wrzlprmft

Reputation: 4415

How do I explicitly not support pickling?

I have written a Python class that cannot possibly support pickling. Still, every now and then a user tries to pickle instances of this class, which leads to confusing errors. Therefore I wish to throw a custom, informative error message whenever any attempts to pickle instances of my class are made.

How do I best go about doing this? I am particularly interested in solutions that have a broad coverage, i.e., do not only work for the standard-library pickle but also for alternatives to it.

As to what I’ve found so far, I’ll write a self-answer, but I am not sure whether that’s the best way.

Upvotes: 1

Views: 124

Answers (1)

Wrzlprmft
Wrzlprmft

Reputation: 4415

From reading the documentation, I gathered that if the class has a __getstate__ method, it will be called when a pickling attempt is made. Therefore, a solution is to overwrite this method to raise an exception, for example:

import pickle

class Foo(object):
    def __getstate__(self):
        raise pickle.PickleError("No pickling for Foo.")

This appears to work:

some_foo = Foo()
try:
    pickle.dumps(some_foo)
except pickle.PickleError:
    print("Error raised.")
else:
    raise AssertionError("Error not raised")

Upvotes: 3

Related Questions