text processing: variable interpolation and more

Christian Tanzer tanzer at swing.co.at
Mon Sep 10 03:00:27 EDT 2001


weeks at vitus.scs.agilent.com (Greg Weeks) wrote:

> Oleg Broytmann (phd at phd.pp.ru) wrote:
> : print "Dear %(recipient)s:" % dict  ...
> 
> :    will extract dict[recipient] and put it into the string as string. More
> : details in Python docs about overloaded operator %.
> 
> Thanks.  I (obviously) was only aware of (s % d) with d a tuple, despite
> the fact that my textbook describes both cases in the same sentence.  Oops!
> 
> Still, with *two* dictionaries you can capture the entire scope.  Or,
> rather, you could in 1.5.2.

You might want to try something like this:

class Scope :
    """Capture global and local variables visible in caller's scope.

       The index operator also supports expressions as indices and will
       return the result of such expressions as evaluated in the caller's
       scope.

       The supplied index operator allows Scope objects to be used as
       mapping arguments for the string formatting operator `%s':
       
       >>> "42*3 == %(42*3)d" % Scope ()
       '42*3 == 126'
    """
       
    def __init__ (self, globals = {}, locals = {}) :
        self.globals = globals
        self.locals  = locals 
    # end def __init__
    
    def __getitem__ (self, index) :
        return eval (index, self.globals, self.locals)
    # end def __getitem__

With some black magic you can make Scope pick up the caller's global
and local variables all by itself.

-- 
Christian Tanzer                                         tanzer at swing.co.at
Glasauergasse 32                                       Tel: +43 1 876 62 36
A-1130 Vienna, Austria                                 Fax: +43 1 877 66 92





More information about the Python-list mailing list