3 ms·
Might not work in some special cases though. Try: def foo(): a = 4 def bar(): print("a = {a}".format(**locals())) bar()
by quarktasche 11y ago
Might not work in some special cases though. Try:
def foo():
a = 4
def bar():
print("a = {a}".format(**locals()))
bar()
foo()
which will raise a KeyError, while it will work fine if you add a
print(a)
to the end of bar().
- gcr 11y agoIn this case, 'a' isn't a local variable binding though.
- pyre 11y agoRight, but it's accessible in scope though. It's just a "gotcha" for that method that might be easy to overlook if you aren't paying attention (or if someone with less experience stumbles onto this 'trick' in production code).
- fragmede 11y agoActually, if you reference 'a' at all in bar, it will work: def foo(): a = 4 def bar(): a print("a = {a}".format(**locals())) bar() foo() successfully prints a = 4 which is a bit confusing, but makes sense if you think about it.