single/double quote escape interpolation

Manuel Garcia news at manuelmgarcia.com
Tue Jul 8 14:48:15 EDT 2003


On 8 Jul 2003 02:15:38 GMT, bokr at oz.net (Bengt Richter) wrote:

>Might want to mention that somedict only has to act like a dict, not necessarily *be*
>a dict. I.e., supporting __getitem__ suffices, so you can synthesize anything you like
>from the key passed. E.g.,
>
> >>> class AsIs(object):
> ...     def __getitem__(self, key): return '%(' + key + ')s'
> ...
> >>> somedict = AsIs()
> >>> "why don't we drop by the %(where)s and %(dowhat)s a few?" % somedict
> "why don't we drop by the %(where)s and %(dowhat)s a few?"
>
>Maybe that was a little weird ;-) How about,
>
> >>> class RU(object):
> ...     def __getitem__(self, key):
> ...         res = list(key.upper())
> ...         res.reverse()
> ...         return ''.join(res)
> ...
> >>> somedict = RU()
> >>> "why don't we drop by the %(where)s and %(dowhat)s a few?" % somedict
> "why don't we drop by the EREHW and TAHWOD a few?"

This is a really great trick!

When I am debugging I always have a lot of code like this:

    print 'variable_name: %r' % (variable_name,)

And it bugs me that I have to type in the variable name twice.  But
using your trick, I might do:

##################

import sys

class VarReport(object):
    def __getitem__(self, key):
        f = sys._getframe(1)
        if f.f_locals.has_key(key):
            v = f.f_locals[key]
        elif f.f_globals.has_key(key):
            v = f.f_globals[key]
        else:
            raise NameError('name %r is not defined') % (key,)
        return '%s: %r' % (key, v)

VarReport = VarReport()

longname_a = 7
longname_b = 12

print '%(longname_a)s; %(longname_b)s' % VarReport

##################

Manuel




More information about the Python-list mailing list