string interpolation with both local and module variables?

Graham Guttocks graham_guttocks at yahoo.co.nz
Tue May 1 20:11:40 EDT 2001


Greetings,

I'm trying to do string interpolation on a textfile containing
references to variables both in the local function, and also in one of
my modules.

As demonstrated below, this doesn't seem to work because variables in
the calling function aren't available to the function doing the
interpolation.  Any ideas?

 def printmsg():
     foo = 'FOO'
     message = makemessage('/tmp/test.txt')
 
 def makemessage(file):
     fp = open(file)
     template = fp.read()
     from Defs import *
     text = template % vars()
     return text

/tmp/test.txt contains:

Hello %(USERNAME)s, how do you %(foo)s?

>>> printmsg()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 3, in printmsg
  File "<stdin>", line 5, in makemessage
KeyError: foo


__________________________________________________
Do You Yahoo!?
Yahoo! Auctions - buy the things you want at great prices
http://auctions.yahoo.com/




More information about the Python-list mailing list