Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
variables in f-string
#1
is it OK to set variables in an f-string? i need to call an expensive (e.g. slow) function to get a value that is needed in 3 places in an f-string and again in a 2nd f-string. calling this function 4 times is bad and also can cause other problems. currently i call it once and assign its return value to a short variable and use that in the f-strings. now i'm wanting to squeeze this into one line:
[stupid example code]
print(f'{x=stupid_slow_function()} {x} {x} {x}',some_other_big_string,f'foo{x}bar}')
[/stupid example code]
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
Replace '=' with the walrus operator := and wrap the assignment parentheses. So ...


print(f'{(x:=stupid_slow_function())} {x} {x} {x}',some_other_big_string,f'foo{x}bar}')
Gribouillis likes this post
Reply
#3
what is the difference between = and :=?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#4
ah, the disadvantage of using 3.7 documentation. gotta fix that.
Tradition is peer pressure from dead people

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


Forum Jump:

User Panel Messages

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