Op Tuesday 5 May 2015 13:08 CEST schreef Peter Otten: > Cecil Westerhof wrote: > >> I now defined get_message_slice: >> ### Add step >> def get_message_slice(message_filename, start, end): > > Intervals are usually half-open in Python. I recommend that you > follow that convention.
I will change it. >> """ >> Get a slice of messages, where 0 is the first message >> Works with negative indexes >> The values can be ascending and descending >> """ >> >> message_list = [] >> real_file = expanduser(message_filename) >> nr_of_messages = get_nr_of_messages(real_file) >> if start < 0: >> start += nr_of_messages >> if end < 0: >> end += nr_of_messages >> assert (start >= 0) and (start < nr_of_messages) > > You should raise an exception. While asserts are rarely switched off > in Python you still have to be prepeared, and an IndexError would be > a better fit anyway. OK. > Should you later decide that a database is a better fit you can > change read_messages() to return a class that transparently accesses > that database. Again, most of the work is already done: > > class Messages(collections.Sequence): > def __init__(self, filename): > self.filename = filename) > def __getitem__(self, index): > # read record(s) from db > def __len__(self): > # return num-records in db > > def read_messages(filename): > return Messages(filename) Another thing I have to look into. :-D > By the way, where do you plan to use your functions? And where do > the indices you feed them come from? In my case from: get_random_message and: dequeue_message Both also in: https://github.com/CecilWesterhof/PythonLibrary/blob/master/filebasedMessages.py I should write some documentation with those functions. ;-) I have a file with quotes and a file with tips. I want to place random messages from those two (without them being repeated to soon) on my Twitter page. This I do with ‘get_random_message’. I also want to put the first message of another file and remove it from the file. For this I use ‘dequeue_message’. -- Cecil Westerhof Senior Software Engineer LinkedIn: http://www.linkedin.com/in/cecilwesterhof -- https://mail.python.org/mailman/listinfo/python-list