4 ms·
The motivation for PEP-0498 given in the article was the difference in verbosity between these two lines: "{} {}".format(a, b) "%s %s" % (a, b,) That's no
by richard_todd 11y ago
The motivation for PEP-0498 given in the article was the difference in verbosity between these two lines:
"{} {}".format(a, b)
"%s %s" % (a, b,)
That's not very convincing. I was hoping this article would make a good case for interpolated strings, since it's starting to feel like Python is having an identity crisis. Type annotations especially took me by surprise, but string interpolation is another good example of an addition that doesn't feel like Python (imho, anyway).
- jdnier 11y agoThe more common case for me is to name the parameters. Especially with longer variable names, this gets tedious fast. Given >>> very_long_var_name_1 = 'spam' >>> very_long_var_name_2 = 'ham' compare >>> # Explicit but tedious and doesn't help readability: >>> print('{very_long_var_name_1}: {very_long_var_name_2}'.format( ... very_long_var_name_1=very_long_var_name_1, ... very_long_var_name_2=very_long_var_name_2)) spam: ham with >>> # Explicit but somehow feels dirty: >>> print('{very_long_var_name_1}: {very_long_var_name_2}'.format( ... **locals())) spam: ham and >>> # Still fits on one line. I think f prefix makes intent clear. >>> print(f'{very_long_var_name_1}: {very_long_var_name_2}') spam: ham
- toyg 11y agoThing is, * * locals() "feels dirty" but does exactly the same thing as f''. Except f'' does it implicitly, hiding dirt under the carpet. One day, that dirt will turn something into a bug; which is exactly why the Zen says "explicit is better than implicit". The best way imho would be: vars = {'short1': very_long_var_name1, 'short2': very_long_var_name2} print('{short1} {short2}'.format(**vars)) Easy and extremely unlikely to ever include the wrong variable.
- spicyj 11y agoExcept a linter or static analyzer can easily be taught to understand f"", but it's essentially impossible to reason statically about locals().
- deleted 11y ago[deleted]
- mixmastamyk 11y ago> Thing is, * * locals() "feels dirty" but does exactly the same thing as f'' That's false, it does not do that. It converts the string into the equivalent format call at compile-time. RTFP ;)