
![]() | Variable interpolation with vars:
class C(B):
def write(self):
local_var = -1
s = '%(local_var)d %(global_var)d %(a)s' % vars()
|
![]() | Problem: vars() returns dict with local variables and the string needs global, local, and class variables |
![]() | Primary solution: use printf-like formatting:
s = '%d %d %d' % (local_var, global_var, self.a) |
![]() | More exotic solution:
all = {}
for scope in (locals(), globals(), vars(self)):
all.update(scope)
s = '%(local_var)d %(global_var)d %(a)s' % all
(but now we overwrite a...)
|