using generators with format strings

Bengt Richter bokr at
Tue Jul 27 20:56:40 CEST 2004

On Tue, 27 Jul 2004 11:28:29 -0400, Christopher T King <squirrel at WPI.EDU> wrote:

>On Tue, 27 Jul 2004, John Lenton wrote:
>> does anyone else get the feeling that (str %) should have a third
>> behaviour wrt generators? By this I mean that str % seq is one
>> behaviour, str % dict is another, and there should be a str % iter,
>> probably consuming items from the iterator up to the number of
>> arguments of the format string?
>The only argument I see against this is that it could break existing code
>of the form '%r' % some_object, where some_object could easily be an
>iterable object (say, a numarray array).  Of course, limiting it to only
>generators rather than iterators in general would fix this, but then the
>benefit gained seems too small to justify the cost of implementing another
>exception to the rule.

You could subtype str and override __mod__ to do it (which I'll leave
as an exercise ;-)  e.g.,

    class MYFMT(str):
        def __mod__(self, args):

and then use it like

    MYFMT('formatted string args from generator: %s %r %(mapping_key)s') % generator

Then you could make it do anything you like without changing current python, even
mixing in mapping usage if you wanted to.

Bengt Richter

More information about the Python-list mailing list