Making string-formatting smarter by handling generators?
gagsl-py2 at yahoo.com.ar
Thu Feb 28 03:27:35 CET 2008
En Wed, 27 Feb 2008 20:40:04 -0200, Tim Chase
<python.list at tim.thechases.com> escribió:
>>> Note that your problem has nothing to do with map itself.
>>> String interpolation using % requires either many individual
>>> arguments, or a single *tuple* argument. A list is printed
>>> as itself.
> Just as an exercise to understand this better, I've been trying
> to figure out what allows for this interpolation. It doesn't
> seem to be via duck-typing:
> >>> # what does a tuple have that a list doesn't
> >>> tuple_set = set(dir(tuple()))
> >>> list_set = set(dir(list()))
> >>> tuple_set - list_set
> class LikeATuple(list):
> def __getnewargs__(self, *args, **kwargs):
> pass # now have everything dir(tuple()) has
> f = LikeATuple((1,2,3))
> print "%s, %s, %s" % f
> However, if I create a class that derives from a tuple(), it
> seems to work fine:
> class MyTuple(tuple):
> f = MyTuple((1,2,3))
> print "%i, %i, %i" % f
> it works fine. Is there some secret attribute that I'm missing?
Yes: the class itself :)
The code checks whether the right argument is a tuple (or subclass of), or
a generic mapping. Checking *only* for tuples allows one to usually write
"%s" % thing, and only bother to write "%s" % (thing,) when such `thing`
could actually be a tuple.
Mappings don't have that problem, because the left operand must be written
in a different form so Python knows when to treat the right operand as a
See my previous response to Steven D'Aprano.
More information about the Python-list