[Python-ideas] String formatting and namedtuple

Guido van Rossum guido at python.org
Tue Feb 17 19:32:17 CET 2009


You can do similar things with .format(), but inside {} the : and !
characters always end the key.

On Tue, Feb 17, 2009 at 12:22 AM, Brandon Mintern <bmintern at gmail.com> wrote:
> 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
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas
>



-- 
--Guido van Rossum (home page: http://www.python.org/~guido/)



More information about the Python-ideas mailing list