Many thanks mrabarnett for the code critic...
On Mon, Jan 9, 2012 at 5:08 PM, MRAB <pyt...@mrabarnett.plus.com> wrote: > On 09/01/2012 22:51, david.gar...@gmail.com wrote: > >> Hello, >> >> I have a class and i return both a key list and dictionary from the >> class. Is it good form to do this? The print helo.__dict__ shows both >> the list and dictionary. >> >> >> >> >>> class Parse_Nagios_Header: >> ... def __init__(self): >> ... self.keylist = [] >> ... self.d = {} >> ... f = open("common.h") >> ... lines = f.readlines() >> ... lines = filter(lambda x: not x.isspace(), lines) >> ... f.close() >> ... for line in lines: >> ... if re.search("CMD", line): >> > > You don't need to use a regex for this. It's better to do this instead: > > if "CMD" in line: > > > ... line = line.lstrip('#define ') >> > > The .lstrip, .rstrip and .strip methods treat the argument as a _set_ > of characters, so that line will strip the characters '#', 'd', 'e', > 'f, 'i', 'n' and ' ' from the left end of the line however many times > they occur. > > > ... line = line.strip() >> ... line.replace('\t', ' ') >> ... line = line.split() >> > > The .split method, when called without an argument (or an argument of > None), will split on a sequence of whitespace characters, but ignore > leading and trailing whitespace. > > Therefore, there is no need to use the .strip method or the .replace > (which will have no effect anyway because it _returns_ its result, > which is then discarded) before the split. > > > ... if len(line) > 2: >> ... pass >> > > The preceding two lines are pointless. Just turn the next line into an > 'if'; it'll have the same effect. > > > ... elif len(line) == 2: >> ... line[1] = int(line[1]) >> ... self.d[line[1]] = line[0] >> ... self.keylist = sorted(self.d.iterkeys()) >> ... def __iter__(self): >> ... return iter(self.keylist, self.d) >> ... >> > [snip] > -- > http://mail.python.org/**mailman/listinfo/python-list<http://mail.python.org/mailman/listinfo/python-list> > -- David Garvey
-- http://mail.python.org/mailman/listinfo/python-list