5 ms·
They missed my favorite trick! locals() will give you a dict of, well, local variables, which generally coincides with what you want, so: a = 4 'A is:
by fragmede 12y ago
They missed my favorite trick!
locals() will give you a dict of, well, local variables, which generally coincides with what you want, so:
a = 4
'A is: {a}'.format(**locals())
works as expected.
- quarktasche 12y agoMight 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 12y agoIn this case, 'a' isn't a local variable binding though.
- pyre 12y 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 12y 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.
- maxerickson 12y agostr.format_map takes a mapping directly (added in 3.2).
- wodenokoto 12y agoWhy not just a = 4 'A is:{}'.format(a)
- x1798DE 12y agoI think the point would be to do something like: a = 3 b = 4 c = 6 "A is {a}, C is {c}, B is {b}".format(**locals()) Then you don't have to figure out specifying order or definitions like ".format(a=a, b=b, c=c)". I'd probably go the more explicit route in production code anyway, but for debugging / unstable development it seems useful.
- wodenokoto 12y agoI'm still not convinced. In order to write the string portion of the code, I need to know the names of the variables in play and I have to order them in them in some order in the string regardless. So I still don't think "A is {a}, C is {c}, B is {b}".format(**locals()) is better than "A is {}, C is {}, B is {}".format(a, c, b)
- pfranz 12y agoI've seen this and tried to avoid it since getting bitten my moving code around and not catching which variables were used. It might have been even more obscured with something like TEMPLATED_STRING.format(locals())
- reidrac 12y agoYou can also: a = 4 'A is: %(a)d' % locals() Perhaps is my experience programming in C, but "format" looks lees familiar and I tend to use the old style formatting.