string interpolation (was: Newbie can't figure out documentation practices)
Fernando Perez
fperez528 at yahoo.com
Fri May 9 16:06:15 EDT 2003
Iwan van der Kleyn wrote:
> Fernando Perez wrote:
>> My point in all of this is that python, while overall incredibly clean in
>> its design, lacks an easy way of accessing object member data for string
>> interpolation.
>
> By design yes, in practice no. In the CookBook you can find a solution
> (or hack if your prefer). Instead of using locals() you use a custom
> class which accesses the 'namespace' of the caller through the
> sys._getframe() function.
>
> Personally I would argue that Python's powerfull introspection
> facilities often negates the call for Yet Another Feature to be included
> in Python :-)
Personally I would argue that for a newbie, the fact that
print "x=%(x)s" % locals()
works
while
print "self.x=%(self.x)s" % locals()
doesn't, and that the solution requires _getframe, should be seen as a
language wart. _getframe is a hackish feature (which I use a lot, in fact
:), which is rather advanced and shouldn't IMHO be necessary for something
as simple as the above. The leading _ should be a 'not for newbies'
warning, if nothing else. Plus, messing with the stack by hand isn't
exactly in the 'blindingly obvious' category, I think ;)
That said, I like your solution quite a bit, so thanks! See comment next:
> class Eval:
> globals = globals()
> def __getitem__(self, key):
> self.locals = sys._getframe(1).f_locals
> key = key % self
> return eval(key, self.globals, self.locals)
which I'd modify to:
class Eval:
def __getitem__(self, key):
self.globals = sys._getframe(1).f_globals
self.locals = sys._getframe(1).f_locals
key = key % self
return eval(key, self.globals, self.locals)
so that it can be placed in a separate module instead of relying on the
current module's globals. Otherwise you'd have to recopy the code to every
module where you want to use it for globals to be correctly accessed.
Best regards,
Fernando.
More information about the Python-list
mailing list