Making string-formatting smarter by handling generators?

Tim Chase python.list at tim.thechases.com
Wed Feb 27 17:40:04 EST 2008


>> 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? 
  Or does string expansion absolutely require a descendent of 
tuple?  This seems contrary to Python's ethos of duck-typing/EAFP 
as this requires a static type and does LBYL...which would 
contribute to my previous confusion.

However, with dictionary lookup, it doesn't care that it's a 
dict, just that it implements the __getitem__ interface:

   class Foo(object):
     def __getitem__(self, name):
       return name.encode('rot13')
   f = Foo()
   print "%(hello)s, %(there)s, %(world)s" % f

Can anybody offer insight into why one is unchangeably based off 
the object-hierarchy, while the other is based off duck-typing?

trying-to-wrap-my-head-around-it'ly yers,

-tkc







More information about the Python-list mailing list