Live data from Hacker News

Python 3's F-Strings: An Improved String Formatting Syntax

realpython.com

91–100 of 147 posts

Re: Python 3's F-Strings: An Improved String Formatting Syntax

#91
post #58

Earlier quoted context omitted.

I would personally be quite against that. That's a pretty large breaking change, with no clear benefit. It doesn't make the feature more discoverable, since you still need to know that using "{}" will cause interpolation. I'd say net zero effect on readability; mostly just individual preference. And potential negative impact on performance.

There would be a __future__ import to turn it on, at least for some number of releases. But yeah, I'm not sure it should ever be the default behavior. It makes most sense to me as a per-module opt-in, but then a __future__ import doesn't make sense. And we've resisted having per-module pragmas, so maybe it's dead in the water.

> And we've resisted having per-module pragmas, so maybe it's dead in the water.

There's a hack for that (no apologies for the self promotion; the project is a just funnin')

https://github.com/boothby/dissert

Re: Python 3's F-Strings: An Improved String Formatting Syntax

#92

From reading the comments in the discussion here, I'm curious why the f-string syntax is so all-over-the-place? - f"{foo}" uses the default format - f"{foo!r}" uses repr to format - f"{foo=}" uses a special-cased debugging introspection - f"{foo:formatstr}" uses the default format with a custom format string - f"{foo:{bar}}" uses a dynamic format string It seems like `!r` and `=` should have been implemented with `:r…

!r is one of a class of conversion flags, others are !a which uses ascii(), !s which uses str(). “=” in the format-spec (the thing that comes after the “:”) is the numeric padding alignment specifier (other alignment specifiers are left “ ”, and center “^”.)

Oh, neat, so I can stack them:

  foo = 'foo'
  print(f"{foo=!r:>20}")
  print(f"{foo.upper()=!r:>20}")
The `=` you pointed out is a special case, however, and not part of the alignment specification. Sadly, this means that the above snippet is not as nicely formatted as I'd like. Still, it does seem useful for these cases:

  print(f"{x=:.2f} {dx=:.2f} {dot_product=:.4f}")

Re: Python 3's F-Strings: An Improved String Formatting Syntax

#93

From reading the comments in the discussion here, I'm curious why the f-string syntax is so all-over-the-place? - f"{foo}" uses the default format - f"{foo!r}" uses repr to format - f"{foo=}" uses a special-cased debugging introspection - f"{foo:formatstr}" uses the default format with a custom format string - f"{foo:{bar}}" uses a dynamic format string It seems like `!r` and `=` should have been implemented with `:r…

You really have to understand how it's translated into actual code, and of course it's Python, so there's some legacy syntax to take into account. A `:` just means call format(lhs, rhs), for example.

You can also actually combine those syntaxes - I often use f"{foo:%Y-%m-%d!r}" to get a quoted, properly escaped date in a specific format, for example.

Re: Python 3's F-Strings: An Improved String Formatting Syntax

#94
post #12

> However, once you start using several parameters and longer strings, your code will quickly become much less easily readable [...] `"Hello, %s %s. You are %s. You are a %s ...` Minor correction: % formatting allows specifying names for dictionary keys too: In [1]: "%(a)s and %(b)s" % {"a":"A", "b":"B"} Out[1]: 'A and B' In fact I had never switched to using str.format as it just never added enough benefit for me ov…

I have mixed feelings about code inside f-strings. It seems like a bit of a slippery slope towards losing track of what's happening. I have been tempted to write things like below because I really just need it for the print. f"Info print for item {hex(do_some_parsing(do_some_conversion(value)))}" Which runs perfectly fine, but at least on my editor syntax highlighting stops working as it is all part of the string. An…

I don’t think it’ll be an issue. This isn’t exactly new ground. We know the results from other languages. There might be some such abuse, but there’s a lot of other ways to abuse expressions and they don’t happen often because it’s just not worth it.

Re: Python 3's F-Strings: An Improved String Formatting Syntax

#95
post #85
post #76

Earlier quoted context omitted.

Also, remember that the first argument to the logging functions is considered to be a format string. So using f-strings is not just less efficient, it is also not robust, unless you do: logging.debug("%s", f"Unexpected, got {got}") because otherwise, if the format string is the first/only argument, and `got` unexpectedly contain `%`, an exception will be raised due to a missing format parameter. (Also, for the loggin…

As the sibling comment points out, it actually doesn't work that way. The first parameter is only treated as a format string _if_ there are arguments. If not, it is treated as a literal string: https://github.com/python/cpython/blob/dcea78ff53d02733ac598...

I stand corrected. Thanks.

(That's what I get for assuming consistent behavior :P)

Re: Python 3's F-Strings: An Improved String Formatting Syntax

#96
post #44

I learned this nice syntax from a tweet yesterday: >>> import datetime >>> now = datetime.datetime.now() >>> f"Today is {now:%m/%d/%Y}." 'Today is 01/20/2021.' No need for now.strftime() in simple string output! https://twitter.com/mariatta/status/1351359518316216321

I love this - didn't realize it was a thing at all! If anyone is curious, this works for any type in Python that implements __format__ ({now:%m/%d/%Y} is equivalent to {now.__format__('%m/%d/%Y')}), and you can (ostensibly) make the format string mean whatever you want.

Re: Python 3's F-Strings: An Improved String Formatting Syntax

#97

Something I find useful, and perhaps isn't widely known is that you can pop curly braces into the format part of an f-string to have dynamic formatting: value = 5/6 precision = 2 print(f"{value:.{precision}f}") > 0.83

This is great, had been hacking around this with formatfor years. Will incorporate this soon.

Re: Python 3's F-Strings: An Improved String Formatting Syntax

#98
post #12

> However, once you start using several parameters and longer strings, your code will quickly become much less easily readable [...] `"Hello, %s %s. You are %s. You are a %s ...` Minor correction: % formatting allows specifying names for dictionary keys too: In [1]: "%(a)s and %(b)s" % {"a":"A", "b":"B"} Out[1]: 'A and B' In fact I had never switched to using str.format as it just never added enough benefit for me ov…

I have mixed feelings about code inside f-strings. It seems like a bit of a slippery slope towards losing track of what's happening. I have been tempted to write things like below because I really just need it for the print. f"Info print for item {hex(do_some_parsing(do_some_conversion(value)))}" Which runs perfectly fine, but at least on my editor syntax highlighting stops working as it is all part of the string. An…

[deleted]

Re: Python 3's F-Strings: An Improved String Formatting Syntax

#99
post #12

> However, once you start using several parameters and longer strings, your code will quickly become much less easily readable [...] `"Hello, %s %s. You are %s. You are a %s ...` Minor correction: % formatting allows specifying names for dictionary keys too: In [1]: "%(a)s and %(b)s" % {"a":"A", "b":"B"} Out[1]: 'A and B' In fact I had never switched to using str.format as it just never added enough benefit for me ov…

I have mixed feelings about code inside f-strings. It seems like a bit of a slippery slope towards losing track of what's happening. I have been tempted to write things like below because I really just need it for the print. f"Info print for item {hex(do_some_parsing(do_some_conversion(value)))}" Which runs perfectly fine, but at least on my editor syntax highlighting stops working as it is all part of the string. An…

I have mixed feelings about just grabbing variables inside strings. Prior to this I had a coworker that really liked using the convention:

  "{value}".format(**locals())
I thought it was clever at first, but this made refactoring really hard because you would move around these strings or variables and lose track of what's happening. Maybe IDEs are better at helping with this in recent years?

Re: Python 3's F-Strings: An Improved String Formatting Syntax

#100

The issue with f-strings is that they can't be used for i18n. AFAIK, it is impossible to make `_(f"Hello, {name}")` work - at least without a preprocessor or very arcane bytecode manipulation magic. This is unlike much uglier but common and well-supported `_("Hello, %(name)s") % {"name": name}`. In the examples I've used `_` as an alias for a `gettext` call - I believe this is a common practice to do something like `…

Not f-strings, but I am partial to something like:

    _("Hello, {name}").format(name=name)
Post reply on HN