[Python-ideas] String formatting and namedtuple

Brandon Mintern bmintern at gmail.com
Tue Feb 17 09:22:08 CET 2009


On Tue, Feb 17, 2009 at 2:47 AM, Christian Tanzer <tanzer at swing.co.at> wrote:
> Please note that the right-hand operand can be a dictionary
> (more specifically, any object implementing `__getitem__()`)
>
> For objects implementing `__getitem__`, the stuff inside the
> parentheses of `%(...)s` can get pretty fancy.

Indeed it can. I had some functionality for templating C programs that
relied on just this. The files would be mostly C code, but then
%-formatting was used to specify certain chunks to be generated by
Python code. The custom class I wrote implemented a __getitem__ class
that broke down the given key into arguments to an indicated function,
eval-ed Python code, and generated the desired C code. This was
super-useful for things like spitting out static const arrays and
specifying the array sizes in the header file without requiring
duplicate human effort.

An example would be the following snippet from a C-template,
num_to_words.ctemplate:

%(array; char * ones; "zero one two three four five six seven eight
nine".split())s

Taking this file, reading it in, and doing %-interpolation with my
custom class would result in the following output:

num_to_words.h:

extern char * ones[10];


num_to_words.c:

#ifndef NUM_TO_WORDS_C
#define NUM_TO_WORDS_C

#include "num_to_words.h"

char * ones = {
    "zero",
    "one",
    "two",
    "three",
    "four",
    "five",
    "six",
    "seven",
    "eight",
    "nine"
};

#endif


So there are some pretty crazy things possible with %-formatting and
custom __getitem__ classes. As long as format can do similar things,
though, I don't think there is a problem.


Brandon



More information about the Python-ideas mailing list