Chris
Chris

Reputation: 31216

How to disable pickling?

I have a class where some user may try to pickle it.

If they do, what I would like to do is:

  1. Call the destructor method of all child items in the object instance
  2. Raise a NotImplemented error

But, I am not sure what overrides I need to define so that whenever pickle tries to serialize this object instance, I can perform those two tasks.

I.E., in pseudo code, is there some analog for:

def __pickle__(self):
  ...

# i.e.
def __<the function pickle looks for when it pickles>__(self):
  del x 
  del y
  del z
  ...
  raise NotImplemented("You Fool! Ahhh!!!")

Upvotes: 1

Views: 580

Answers (1)

gen_Eric
gen_Eric

Reputation: 227270

You can use the __getstate__ method. This will be called when your object is pickled and you can do what you need to here.

def __getstate__(self):
    raise NotImplementedError("You Fool! Ahhh!!!")

Docs: https://docs.python.org/3/library/pickle.html#handling-stateful-objects

Upvotes: 1

Related Questions