re.search (works)|(doesn't work) depending on for loop order

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Sat Mar 22 20:03:52 EDT 2008


En Sat, 22 Mar 2008 17:27:49 -0300, sgharvey <KephnosAnagennao at gmail.com>  
escribi�:

> ... and by works, I mean works like I expect it to.
>
> I'm writing my own cheesy config.ini parser because ConfigParser
> doesn't preserve case or order of sections, or order of options w/in
> sections.

Take a look at ConfigObj http://pypi.python.org/pypi/ConfigObj/

Instead of:

       # Remove the '\n's from the end of each line
       lines = [line[0:line.__len__()-1] for line in lines]

line.__len__() is a crazy (and ugly) way of spelling len(line). The  
comment is misleading; you say you remove '\n's but you don't actually  
check for them. The last line in the file might not have a trailing \n.  
See this:

lines = [line.rstrip('\n') for line in lines]

Usually trailing spaces are ignored too; so you end up writing:

lines = [line.rstrip() for line in lines]

In this case:
       # Compile the regexen
       patterns = {}
       for pattern in pattern_strings:
          patterns.update(pattern: re.compile(pattern_strings[pattern],  
re.VERBOSE))

That code does not even compile. I got lost with all those similar names;  
try to choose meaningful ones. What about this:

patterns = {}
for name,regexpr in pattern_strings.iteritems():
     patterns[name] = re.compile(regexpr, re.VERBOSE))

or even:

patterns = dict((name,re.compile(regexpr, re.VERBOSE))
              for name,regexpr in pattern_strings.iteritems()

or even compile them directly when you define them.

I'm not sure you can process a config file in this unstructured way; looks  
a lot easier if you look for [sections] and process sequentially lines  
inside sections.

             if match:
                content.update({pattern: match.groups()})

I wonder where you got the idea of populating a dict that way. It's a  
basic operation:
content[name] = value

The regular expressions look strange too. A comment may be empty. A  
setting too. There may be spaces around the = sign. Don't try to catch all  
in one go.

-- 
Gabriel Genellina




More information about the Python-list mailing list