Python Forum
trying to learn f-strings - puzzled by format() protocol
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
trying to learn f-strings - puzzled by format() protocol
#5
(Jul-25-2019, 11:37 AM)metulburr Wrote:
(Jul-25-2019, 05:29 AM)Skaperen Wrote: there seems to be a more advanced level of understanding needed to be able to interpret all kings of f-string.
You dont really need to know the inner workings of format to use f-string over format. F-strings are suppose to be more easily understandable as well as less code to type.

i need to, at least, understand what the documentation is trying to say. it describes some formatting, then it says the result is passed to __format__(). is it just the string result that is being passed? what would __format__() do with it, like that?

(Jul-25-2019, 12:28 PM)DeaD_EyE Wrote: It's formatted one time. Here the proof of it:

# explaining with code
class MyFormat(str):
    def __format__(self, fmt_str):
        print('Magic method __format__ was called.')
        fmt_str = fmt_str.strip()
        if 'UPPER' == fmt_str:
            return self.upper()
        elif 'LOWER' == fmt_str:
            return self.lower()
        else:
            return self




my_str = MyFormat('Hello World')

# 3 calls, 3 times formatting
print(f'{my_str: UPPER }')
print(f'{my_str: LOWER }')
print(f'{my_str}')


# the same with the format method
# 3 calls, 3 times formatting
print('{:UPPER}'.format(my_str))
print('{:LOWER }'.format(my_str))
print('{}'.format(my_str))
Output:
Magic method __format__ was called. HELLO WORLD Magic method __format__ was called. hello world Magic method __format__ was called. Hello World Magic method __format__ was called. HELLO WORLD Magic method __format__ was called. hello world Magic method __format__ was called. Hello World

as described in the documentation, calling __format__() with the result would be the 2nd step.

from your example, it is calling there, so i need to understand how that works (but i will read over your code a few times to see if i can pick up on it).

(Jul-25-2019, 05:41 AM)Yoriz Wrote: I don't think it saying its formatted twice, the f string is passed to format() to do the actual formatting.

the documentation describes two steps, the 2nd being the call to __format__(). maybe they worded it badly?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Messages In This Thread
RE: trying to learn f-strings - puzzled by format() protocol - by Skaperen - Jul-25-2019, 08:13 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  print a list strings is fast but printing the joined strings is slow Skaperen 9 3,961 Aug-26-2019, 07:48 PM
Last Post: Skaperen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020