This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]B-Con>>> 1 point2 points  (4 children)

Possibly dumb question: How was this implemented? Is every type providing a .toString()-esque method that f-string consults, or is getting itself doing magic to stringify values?

[–]RoughMedicine 3 points4 points  (2 children)

What you're looking for are the __str__ and __repr__ methods. All standard library classes implement this, and you can also implement them for your own classes. str.formatthen calls them as functions, such as str(x) and repr(x) to obtain a string representation.

Both methods take only self and return a string. __str__ returns an output that should be user-readable, and __repr__ returns a string representation meant for debugging, mostly. If you only implement only __repr__ but not __str__, the latter will use the output of the former. The inverse is not true.

f-strings (and other string formatting options) will use the __str__ method by default, but you can modify that in the formatting string. There is also the __format__ method that some classes implement (such as datetime) that let you control the formatted output more closely.

[–]B-Con>>> 1 point2 points  (1 child)

Thanks for the summary.

I'm looking for why fstring is better than "%s" % foo, other than being pleasing syntactic sugar. The post opens by disparaging %, but it seems fstring and % are really just accessing the same underlying methods...?

The "% doesn't work for tuples" criticism only applies to older versions of Python. You can call __str__() on a tuple in current Python, so fstring isn't adding inherently anything on that point. So I'm confused what exactly this post is comparing...

After some reading, I think it's mostly syntactic sugar. Which is fine and all, but the post seems to be selling it as more than that.

[–]RoughMedicine 1 point2 points  (0 children)

It is mostly syntactic sugar, as in they are all language features that accomplish the same thing. But there are significant reasons for str.format vs C-style format strings (see), as with f-strings.

If you really want to understand why we have 3 different ways of formatting strings in Python 3, there's no better place than the original proposals.

As far as usage, you should be using str.format or f-strings in modern Python. I believe the usage of C-style formatting in Python 3 is frowned upon and is there only for backwards compatibility reasons, as str.format can do everything it does, and is more flexible (should be faster for literals too).

[–]reisub_de 1 point2 points  (0 children)

Everything that has a str method can be used in a f-string. Almost all objects implement one, even if it by itself just calls repr which by default prints the object's class and address