Making string-formatting smarter by handling generators?

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Wed Feb 27 21:43:16 EST 2008


On Thu, 28 Feb 2008 00:03:02 -0200, Gabriel Genellina wrote:

> En Wed, 27 Feb 2008 23:18:14 -0200, Steven D'Aprano
> <steve at REMOVE-THIS-cybersource.com.au> escribió:
> 
>> I think there is a good case for % taking an iterator. Here's an
>> artificial example:
>>
>> def spam():
>>     while True: yield "spam"
>>
>> spam = spam()
>>
>> "%s eggs tomato and %s" % spam
>> "%s %s bacon tomato %s and eggs" % spam "%s %s %s %s %s %s %s %s
>> truffles and %s" % spam
>>
>> The iterator could be arbitrarily complex, but the important feature is
>> that the % operator lazily demands values from it, taking only as few
>> as it needs. If the iterator is exhausted early, it is an error.
> 
> The % operator has to know whether you want to convert the iterator
> itself, or the items yielded. Currently it checks whether its argument
> is a tuple, and takes its contents. "%s" % "hello" is a (very handy)
> shortcut for "%s" % ("hello",). 

You may not have noticed I said iterator, not iterable. I would expect 
that general iterables like strings and lists would continue to work as 
they do now.

[...]
> Changing the % operator this way isn't a good idea, but your suggestion
> could be used in another string method/operator/library function.

That's also a good option.


-- 
Steven



More information about the Python-list mailing list