
Mike Miller schrieb am 20.07.2015 um 01:35:
csstext += '{nl}{key}{space}{{{nl}'.format(**locals())
This looks a bit better if you ignore the right half, but it is longer and not as simple as one might hope. It is much longer still if you type out the variables needed as kewword params! The '{}' option is not much improvement either.
csstext += '{nl}{key}{space}{{{nl}'.format(nl=nl, key=key, ... # uggh csstext += '{}{}{}{{{}'.format(nl, key, space, nl)
I've long wished python could format strings easily like bash or perl do, ... and then it hit me:
csstext += f'{nl}{key}{space}{{{nl}'
An "f-formatted" string could automatically format with the locals dict. Not yet sure about globals, and unicode only suggested for now. Perhaps could be done directly to avoid the .format() function call, which adds some overhead and tends to double the length of the line?
Is this an actual use case that people *commonly* run into? I understand that the implicit name lookups here are safe and all that, but I cannot recall ever actually using locals() for string formatting. The above looks magical to me. It's completely unclear that string interpolation is happening behind my back here, unless I already know it. I think it's ok to have a "b" string prefix produce a special kind of string and expect people to guess that and look up what it does if they don't know (and syntax like a string prefix is difficult enough to look up already). Having an "f" prefix interpolate the string with names from the current namespace is way beyond what I would expect a string prefix to do. I'd prefer not seeing a "cool feature" added just "because it's cool". If it additionally is magic, it's usually not a good idea. Stefan