string interpolation with both local and module variables?

Steve Holden sholden at holdenweb.com
Wed May 2 08:15:23 EDT 2001


"Graham Guttocks" <graham_guttocks at yahoo.co.nz> wrote in message
news:mailman.988762323.7975.python-list at python.org...
> 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
>
I would be hesitant to rely on interpolation of variables from a Python
namespace anyway, because it's likely the namespaces will get polluted with
other variables you want to use for other purposes. I would seem to make
much more sense to me to pass the dictionary through as a second argument,
as in (untested):

 def printmsg():
     message = makemessage('/tmp/test.txt', {'USERNAME': 'friend', 'foo':
'FOO'})

 def makemessage(file, dict):
     fp = open(file)
     template = fp.read()
     text = template % dict
     return text

If you are *determined* to use a module containing assignments to set up the
values for interpolation, this approach would work there too: just import
the module (using import, not from) and use its __dict__ as the dictionary
you want to pass through.

import Defs
message = makemessage('/tmp/test.txt', Defs..__dict__)

Of course this still gives you a dictionary ploouted with __docs__ and its
friends, so I don't know if it helps.

regards
 Steve





More information about the Python-list mailing list