Nifty interpolation hack [was Re: Equivalent 2->> print '%d %d' %(l[i], for i in range(2))?]

Nick Mathewson QnickQm at alum.mit.edu
Thu May 17 21:52:12 EDT 2001


On 18 May 2001 00:04:30 +0200, Carel Fellinger <cfelling at iae.nl> wrote:
 [...]
>Others have shown you proper ways of doing this, so all that's left
>for me is some contrived code:
>
>>>> class C:
>...    def __init__(self, lst):
>...      self.lst = lst
>...    def __getitem__(self,key):
>...      return self.lst[eval(key)]
>...
>>>> l=[1,2,3,4,5,6,7,8,9]
>>>> "%(1)d %(2+3)d" % C(l)
>'2 6'

Holy crud!  This _works_!?  How come I've never seen this before?
It's such a beautiful kluge enabler!  (Has anybody done this before? I
should submit it to that cookbook thingie.)

class SI:
  """Generic string interpolator.  

     >>> '2*3 == %(2*3)s' % SI() 
     '2*3 == 6'
     >>> def lenStatement(s):
     ...   return "len(%(repr(s))s) is equal to %(len(s))s" %SI(locals())
     ...
     >>> lenStatement('abcd')
     "len('abcd') is equal to 4"
  """

  def __init__(self, locals=None):
    if locals == None:
       locals = {}
    self.locals = locals

  def __getitem__(self, key):
    return eval(key, globals(), self.locals)

It's-like-Perl-only-more-expressive-but-not-as-fast-ly Yours,

-- 
 Nick Mathewson    <Q nick Q m at alum dot mit dot edu> 
                    Remove Q's to respond.  No spam.



More information about the Python-list mailing list