method to intercept string formatting % operations

Jean-Michel Pichavant jeanmichel at sequans.com
Fri Feb 5 10:49:00 EST 2010


bradallen wrote:
> Hello,
>
> For container class derived from namedtuple, but which also behaves
> like a dictionary by implementing __getitem__ for non-integer index
> values, is there a special reserved method which allows intercepting %
> string formatting operations? I would like for my container type to
> behave appropriately depending on whether the string formatting
> operation has a string like this :
>
> "whatever %s yadayada" % mycontainer  # needs to act like a tuple
>
> "whatever %(key)s yadayada" % mycontainer  # needs to act like a
> dictionary
>
> I looked through the Python data model docs at <http://docs.python.org/
> reference/datamodel.html#emulating-container-types> but only found
> this:
>
> "If the left operand of a % operator is a string or Unicode object, no
> coercion takes place and the string formatting operation is invoked
> instead."
>
> Thanks!
>
>   
class toto:
    def __getitem__(self, key):
        return 'paf'
    def __str__(self):
        return 'pif'
    def toTuple(self):
        return (1,2,3)


1/ print '%s %s %s' % toto().toTuple()
'1 2 3'
2/ print '%(key)s ' % toto()
'paf'
3/ print '%s' % toto()
'pif'


1/ I don't know how to spare the explicit toTuple conversion, supporting 
tuple() would be tedious
2/ thanks to __getitem__ (duck typing)
3/ thanks to __str__

Anyway why would you want to use the tuple form ? it's beaten in every 
aspect by the dictionary form.


JM

"If you need something call me, I'll tell you how to live without it" 
(Coluche, about politicians)



More information about the Python-list mailing list