[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.python

Re: Making string-formatting smarter by handling generators?

Gabriel Genellina

2/28/2008 2:28:00 AM

En Wed, 27 Feb 2008 20:40:04 -0200, Tim Chase
<python.list@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
> set(['__getnewargs__'])
>
> 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):
> pass
> 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
mapping.
See my previous response to Steven D'Aprano.

--
Gabriel Genellina