Sometimes one has to parse programmatically some file containing
First, let me introduce the code:</p>
Neat, huh? As promised in the title, this is functional. And yes, I am
aware of ConfigParser</a>, but I do not need its full power, and also I
have found some problems with files containing Unicode</a> strings.</p>
I think this is one of the most beautiful snippets of code I have ever
written in Python: it makes just one thing well, and it is terse and
concise. Moreover, it is quite easy to explain.</p>
I have just written that it is easy to explain how this works. Okay, I
will dissect this beast one line at a time, starting at the innermost.
But first, a quick introduction to key=value</code> pairs. In the world of systems administration this means
configuration files most of the time. Also, one thing I like is
functional programming</a>, but in the real world one ends up making
almost all of the code in imperative</a> style. Python allows some
functional constructs, and sometimes I like to use them to make code
most concise, because it express better what the code is trying to do or
just because I wanted to melt my mind doing some functional tricks.</p>
from</span> itertools import</span> imap, ifilter
config_items = lambda</span> iterable:
imap(lambda</span> (k, v): (k.strip(), v.strip()),
imap(lambda</span> s: s.split("="</span>, 1</span>),
ifilter(lambda</span> s: s and</span> not</span> s.startswith("#"</span>),
imap(lambda</span> s: s.strip(), iterable))))
</code></pre>
How does it work</h2>
imap()</code> and ifilter</code>:</p>
perezdecastro.org · Dec 12, 2009
Python recipe: Functional config file parsing
0Sign in to vote or save
This page cannot be shown here. You can still read it on the original site — the toolbar below keeps your place in the directory.
Sometimes one has to parse programmatically some file containing key=value pairs. In the world of systems administration this means configuration files most of the time. Also, one thing I like is functional programming , but in the real world one ends up making almost all of the code in imperative style. Python allows some functional constructs, and sometimes I like to use them to make code…

Comments
Nothing yet. Say the first thing.
Sign in to join the conversation.