Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!feeder.erje.net!1.eu.feeder.erje.net!newsfeed.pionier.net.pl!feed.xsnews.nl!border03.ams.xsnews.nl!feeder04.ams.xsnews.nl!abp002.ams.xsnews.nl!frontend-F10-20.ams.news.kpn.nl From: Cecil Westerhof Newsgroups: comp.lang.python Subject: Step further with filebasedMessages Organization: Decebal Computing X-Face: "(y8cC@tg_12{">GF'UXTW]FHI2wMiZNrnf'1EFQ&O#$m:f#O7+7}kR,v+Pti8=Vi/Z"g^?b"E X-Homepage: http://www.decebal.nl/ Date: Tue, 05 May 2015 10:52:54 +0200 Message-ID: <87oalzh0d5.fsf@Equus.decebal.nl> User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/24.3 (gnu/linux) Cancel-Lock: sha1:WHuJnobMVegHz2BK/9w/4tShtKY= MIME-Version: 1.0 Content-Type: text/plain Lines: 68 NNTP-Posting-Host: 81.207.62.244 X-Trace: 1430816389 news.kpn.nl 21169 81.207.62.244@kpn/81.207.62.244:58998 Xref: csiph.com comp.lang.python:89946 I now defined get_message_slice: ### Add step def get_message_slice(message_filename, start, end): """ 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) assert (end >= 0) and (end < nr_of_messages) if start > end: tmp = start start = end end = tmp need_reverse = True else: need_reverse = False with open(real_file, 'r') as f: for message in islice(f, start, end + 1): message_list.append(message.rstrip()) if need_reverse: message_list.reverse() return message_list Is that a good way? I also had: def get_indexed_message(message_filename, index): """ Get index message from a file, where 0 gets the first message A negative index gets messages indexed from the end of the file Use get_nr_of_messages to get the number of messages in the file """ real_file = expanduser(message_filename) nr_of_messages = get_nr_of_messages(real_file) if index < 0: index += nr_of_messages assert (index >= 0) and (index < nr_of_messages) with open(real_file, 'r') as f: [line] = islice(f, index, index + 1) return line.rstrip() But changed it to: def get_indexed_message(message_filename, index): """ Get index message from a file, where 0 gets the first message A negative index gets messages indexed from the end of the file Use get_nr_of_messages to get the number of messages in the file """ return get_message_slice(message_filename, index, index)[0] Is that acceptable? I am a proponent of DRY. Or should I at least keep the assert in it? -- Cecil Westerhof Senior Software Engineer LinkedIn: http://www.linkedin.com/in/cecilwesterhof