string interpolation (was: Newbie can't figure out documentation practices)
Iwan van der Kleyn
null at nul.net
Fri May 9 15:29:47 EDT 2003
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 :-)
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018
and
http://www.python.org/doc/current/lib/module-sys.html
# __________________________________________
#example
import sys
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)
class Test:
def go(self, b):
c = 'locals'
self.d = 'object attributes'
return 'Eval evaluates %(a)s, %(b)s, %(c)s and even %(self.d)s'
% Eval()
a = 'globals'
print Test().go('parameters')
More information about the Python-list
mailing list