Making string-formatting smarter by handling generators?

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Wed Feb 27 21:03:02 EST 2008


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",). Consider the following:

py> L = ["hello", "world"]
py> print "%s" % L
['hello', 'world']

Your suggestion would make it behave like this:

py> print "%s" % L
'hello'

Then, if one wants to display the container itself and not the contained  
items, one should wrap *every* list and every sequence/iterator/iterable  
object into an one-element tuple. Currently this is only required for  
tuples.

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

-- 
Gabriel Genellina




More information about the Python-list mailing list