replace %(word) in a string

Peter Otten __peter__ at web.de
Thu Sep 18 02:38:14 EDT 2003


Max M wrote:

> Fred Pacquier wrote:
> 
>> Yes, that's a wonderful feature. Recently though, I've wondered a couple
>> of times : is there an easy way to substitute with both local AND global
>> variables ?...
> 
> It can often be a good idea to create an adapter/pattern for string
> substitutions. Then the wrapper can "massage" the dict values before
> they go into the string.
> 
> Here only a simple version is needed though (untested).
> 
> class Wrapper:
> 
>      def __getitem__(self, key):
>           return locals().get(key, globals[key])
> 
> 
> 'Some string sub %(some_var)s' % Wrapper()

I fear that the locals() you access with your wrapper class are the local
variables of the Wrapper.__getitem__() method. Also globals()[key] is
evaluated on *every* call of __getitem__() and thus fails if you try to
access a local variable that does not shade a global variable.
Assuming class Wrapper and client code are both in the same module, your
code is pretty much equivalent to

'Some string sub %(some_var)s' % globals()

Peter





More information about the Python-list mailing list