3 ms·
Interesting; I hadn't seen that before, and as soon as I saw it I thought "ooh shiny!". Is there a quick reason why I shouldn't use it?
by matheist 11y ago
Interesting; I hadn't seen that before, and as soon as I saw it I thought "ooh shiny!". Is there a quick reason why I shouldn't use it?
- mixmastamyk 11y agoIt isn't forbidden, just that it might leak information, doesn't perform well, and is unsightly. Py 3.6 should have the syntax to simplify, without locals/globals: f'Hello, {name} {age}'
- dagss 11y agoAs for leaking info, your Py3.6 example leaks exactly as much (i.e., what is referenced in the literal). In fact you could consider it syntactic sugar for the locals() (although faster I guess).
- jonathan_s 11y agoYes, but it's unsafe for another reason. The new syntax can be verified statically by tools like Pylint. A call to locals() is hard to verify. The locals() function itself could for instance have been replaced by something else. When using locals(), you won't know until execution time if a local variable, required for the interpolation is missing. Even worse, linter tools (pylint, pyflakes, jedi, ...) are now going to tell you that certain variables are not used, and people are going to remove it without thinking that somewhere a locals() call is going to use it. This is very bad. Actually, the effects of using locals() cannot be verified statically, even more because locals() is also a writable dict. For f-strings, the name bindings are static, and editors are going to understand it while editing.
- njharman 11y ago> The locals() function itself could for instance have been replaced by something else So could .format, or any|everything. Also, where do you think Python looks for {foo}? I'll give you a hint, it starts with "l" and ends with "ocals".
- stdbrouw 11y ago> This is very bad. There's no need for hyperbole. The fact that `locals()` doesn't work well with linters is a bummer, but compared to a multitude of other code smells it's pretty mild and harmless.