3 ms·
I had a co-worker who like the convention: >>> 'User {user} has logged in and did an action {action}.'.format(**locals()) 'User Jane Doe has logged in and
by pfranz 7y ago
I had a co-worker who like the convention:
>>> 'User {user} has logged in and did an action {action}.'.format(**locals())
'User Jane Doe has logged in and did an action buy.'
I thought it was clever at first, but noticed it was frustrating to refactor because it was hard to see the scope of variables (especially if the template string is defined elsewhere). I don't lean heavily on IDEs, but at the time it would flag many required variables as unused because it couldn't grok this.
Do you find the same problems when using f strings?
- DonaldPShimoda 7y ago>>> 'User {user} has logged in and did an action {action}.'.format(**locals()) D: To me, this is pretty gross. This implicitly requires all the correct variables to be bound in the local scope, and there's no easy way to check that this is the case without reading all of the code leading up to this point (which is bad, in my opinion). Because what this really does is create string-level variables `user` and `action` and pass the values of similarly-named (i.e., shadowed) variables in the outer (but still local) scope in their place. This is why IDEs struggle with this: they can't simply know the contents of the dictionary returned by the function `locals()` without actually executing the code (unless they special-case calls to functions named `locals`, but this causes problems if the user ever shadows this name). F-strings directly use the bound variables in the outer (but still local) scope: >>> f'User {user} has logged in and did an action {action}.' 'User Jane Done has logged in and did an action buy.' This avoids the shadowing problem, thus making it easy to use with IDEs and (IMO) easier to grok while reading directly, although maybe most people don't think about shadowing to the same extent I do and wouldn't be as bothered by this in general. Still, the IDE support is incredibly useful.
- baq 7y agothere are python implementations where locals() is unavailable or available at significant cost.
- kragen 7y ago> Do you find the same problems when using f strings? No, you can't define f strings elsewhere, and in theory your IDE can statically analyze them just as the Python interpreter does. In practice, your IDE might suck, I don't know.