Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
How to prevent unpickl'able attributes to get serialized
#!/usr/bin/env python3
import logging
import pickle
module_logger = logging.getLogger('examplepickling')
module_logger.setLevel(logging.DEBUG)
fh = logging.FileHandler('exppickle.log')
fh.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
ch.setFormatter(formatter)
module_logger.addHandler(fh)
module_logger.addHandler(ch)
class Person:
def __init__(self, name=None):
if name:
self.name = name
def to_pickle(self):
pickle.dump(self, open("jar_of_pickles.pkl", 'wb'))
pass
@classmethod
def from_pickle(cls):
if cls is Rick:
print("Pickle-Rick!")
return pickle.load(open("jar_of_pickles.pkl", "rb"))
def __getstate__(self):
d = dict(self.__dict__)
if "logger" in d.keys():
del d['logger']
return d
def __str__(self):
return self.name
class Rick(Person):
def __init__(self):
super().__init__("Rick")
class Morty(Person):
def __init__(self):
self.logger = module_logger.getChild("{}".format(self.__class__.__name__))
self.logger.warning("Creating a new Morty")
super().__init__("Morty")
def __setstate__(self, state):
self.__dict__.update(state)
self.logger = module_logger.getChild("{}".format(self.__class__.__name__))
def write_down(self, important_stuff):
self.logger.warning("{} writes down {}.".format(self.name, important_stuff))
if __name__=="__main__":
r = Rick()
print(r)
m = Morty()
print(m)
m.write_down("something for Homework")
r.to_pickle()
pr = r.from_pickle()
m.to_pickle()
pm = m.from_pickle()
print(pm)
pm.write_down("Scenario 4 Instructions".upper())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment