Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #18726 > unrolled thread

Re: classes and __iter__

Started byMRAB <python@mrabarnett.plus.com>
First post2012-01-10 01:08 +0000
Last post2012-01-10 01:08 +0000
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: classes and __iter__ MRAB <python@mrabarnett.plus.com> - 2012-01-10 01:08 +0000

#18726 — Re: classes and __iter__

FromMRAB <python@mrabarnett.plus.com>
Date2012-01-10 01:08 +0000
SubjectRe: classes and __iter__
Message-ID<mailman.4566.1326157685.27778.python-list@python.org>
On 09/01/2012 22:51, david.garvey@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]

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web