Re:PyFormat – Practical examples of old and new style string...
by quarktasche on Wednesday April 15, 2015 @06:06PM
(#9384521)
Might not work in some special cases though. Try:
which will raise a KeyError, while it will work fine if you add a
to the end of bar().
[ Parent
| on HN ]
Re:PyFormat – Practical examples of old and new style string...
by fragmede on Wednesday April 15, 2015 @06:16PM
(#9384588)
Actually, 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.
Re:PyFormat – Practical examples of old and new style string...
by gcr on Wednesday April 15, 2015 @06:24PM
(#9384634)
In this case, 'a' isn't a local variable binding though.
Re:PyFormat – Practical examples of old and new style string...
by pyre on Thursday April 16, 2015 @02:01AM
(#9386110)
Right, 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).