I have inherited a Python script that picks people to make cake for the office each week. In doing so, it maintains a list of people who want to make cake, as well as their email addresses, the last time they made cake and some other things. It stores all of them in a self appending object seen below:
import datetime as dt
import pickle
class Person():
name_list=[]
def __init__(self,name,email):
self.name=name
self.email=email
self.lastCake=dt.datetime.strptime('01011990', '%d%m%Y').date()
self.weight=0
self.update_weight()
Person.name_list.append(self)
def __repr__(self):
return "%s: %i"%(self.name,self.weight)
def __str__(self):
return "%s: %i"%(self.name,self.weight)
def __lt__(self,other):
return self.weight < other.weight
def update_weight(self,now=dt.date.today()):
days_since_cake=now-self.lastCake
self.weight=int(days_since_cake.days)
def make_cake_list():
Person('Alice','FAKE@FAKE.com')
Person('Bob','FAKE@FAKE.com')
Person('Cath','FAKE@FAKE.com')
Person('Dave','FAKE@FAKE.com')
Because this script monitors and sends/receives emails, it runs constantly, and thus occasionally gets shut down when the system is rebooted/power outages/it crashes. This means that the Person object is written/read to/from a file, and Pickle is used to do this with the two functions:
def save_cake_list(people):
with open("cake_list.dat",'w') as f:
pickle.dump(people,f)
def read_cake_list():
with open("cake_list.dat",'r') as f:
return pickle.load(f)
All fairly standard. Except because of how its set up and how it maintains its lists, its a real pig to add new people and then keep track of who you have added (a few names are hard coded in, but I want to get rid of that feature. The less often I have to poke around in the guts of the script, the better!). And with Pickle, a human cant read/edit the file it creates.
So, is there a way to take the object Person (and its all-important, self-appending name_list
) and pass it to a human readable file? XML files spring to mind, but methods I have looked at dont seem to handle the self-appending list system I have here and I dont have a lot of experience with them.
There is an addPerson
function that isnt too bad, so I could always just store a list of people and emails, read that in and shove it in the function, but I would lose the weight (how long since a person last made cake).
Thoughts?
EDIT: I dont believe this is the same as the Dictionary to Serial to Dictionary question elsewhere, as I think converting my Class to Dictionary would lose a key piece of functionality required elsewhere in the code.
However, I am not familiar with Dictionaries, so if I am wrong, please do provide a MWS and explain why Dictionaries would work.