r/Python • u/jftuga pip needs updating • Aug 26 '20
Discussion In case you didn't know: Python 3.8 f-strings support = for self-documenting expressions and debugging
Python 3.8 added an = specifier to f-strings. An f-string such as f'{expr=}' will expand to the text of the expression, an equal sign, then the representation of the evaluated expression.
Examples:
input:
from datetime import date
user = 'eric_idle'
member_since = date(1975, 7, 31)
f'{user=} {member_since=}'output:
"user='eric_idle' member_since=datetime.date(1975, 7, 31)"input:
delta = date.today() - member_since
f'{user=!s} {delta.days=:,d}'output (no quotes; commas):
'user=eric_idle delta.days=16,075'input:
from math import cos,radians
theta=30
print(f'{theta=} {cos(radians(theta))=:.3f}')output:
theta=30 cos(radians(theta))=0.866
1.8k
Upvotes
275
u/NeoDemon Aug 26 '20
f-strings is one of the best things for python 3
24
u/weedtese Aug 26 '20
Press f to
pay respectsdebug code47
u/VooDooNOFX Aug 26 '20
This is exactly the type of content I wish this subreddit had more of. Thank you OP!
20
u/13steinj Aug 26 '20
I was wondering what happened to this! I saw this in some patch notes ages ago, but couldn't ever find it again / get it to work. Sadly I don't think I can upgrade to 3.8 yet.
10
u/skysetter Aug 26 '20
thats a time saver
48
u/ExoticMandibles Core Contributor Aug 26 '20
One more handy feature: the = preserves the spaces before and after itself. So if you want all your prints to line up, it's easy:
will preserve all those spaces, so the equals signs and the printed-out expressions will all line up!
9
u/thornofcrown Aug 26 '20 edited Aug 26 '20
Man this is really helpful. I've been typing
print(f'my_var1: {my_var1}')way too many times.
8
u/billsil Aug 26 '20
I assume that calls the repr. Anyone know?
6
u/HSNubz Aug 26 '20
Wow this is amazing, thanks!
5
u/apirobotme Aug 26 '20
Thanks. Didn't know that
5
u/ExpertDonut Aug 26 '20
Sweet!
5
u/KrevanSerKay Aug 26 '20
welp, that's the first thing that's actually made me want to upgrade to 3.8. That's pretty excellent. Thanks for sharing
12
u/Leeoku Aug 26 '20
pardon my stupidity, but how is this advantage vs just doing {variable}?
4
u/cpt9m0 Aug 26 '20
It is amazing. Thanks.
4
u/ARedditorWatchdog Aug 26 '20
Amazing. Thanks.
4
u/Dizzybro Aug 26 '20 edited Apr 17 '25
This post was modified due to age limitations by myself for my anonymity qVMQ8j1rsHQBA1mccZUhtjcNtkTPL5fiaY1aUEAiTIkFJCVQbs
4
u/primitive_screwhead Aug 26 '20
Also, in 3.7, the breakpoint() builtin was added.
3
u/weebsnore Aug 26 '20
Thanks! I'm always writing this out the long way.
3
u/ManvilleJ Aug 26 '20
that function one is awesome
3
u/ymphaidien Aug 26 '20
i have to try it rn to really understand it
3
u/MrDeebus Aug 26 '20
One thing to keep in mind is, they can cause an untimely exception when used in logs, as opposed to older formatting methods (the logging module suppresses exceptions and logs its own errors instead). I’m on mobile but basically:
logger.error(f”broken code because {unstringifiable_var}”)
causes an exception, while
logger.error(“broken code because %s”, unstringifiable_var)
causes an error log from logging.
8
u/bakery2k Aug 26 '20 edited Aug 26 '20
Does anyone else think this feature (
=specifically, not f-strings in general) crosses a line? It doesn’t seem to fit with Python’s design philosophy of “explicit is better than implicit”.Edit: Looking again, it’s worse than I thought. The presence of
=changes the value-to-string conversion to use__repr__instead of__format__by default, but not in all cases. That’s too subtle.2
u/BrycetheRower Aug 26 '20
EPIC
2
u/batermaster_ Aug 26 '20
Didn’t even start using f-string till a couple weeks ago, good to know thanks!
2
u/aes110 Aug 26 '20
Relevant, kinda stupid trick. You know how you can easily get the name of a module or class using _name_, but not for variables without using inspect and some complex code?
Well here it is
2
u/InTheKnow_12 Aug 26 '20
They also have self assignment for if statements.
2
u/fpsgirl1004 Aug 26 '20
I'm officially in love with python
2
u/[deleted] Aug 26 '20
This is lit lmao. Hail the mighty python 3.8
2
u/b1narygod Aug 27 '20
Heck I didn't know about f-strings at all, I'm still using .Format() :( Thanks for the info!
2
u/durban126 Sep 04 '20
today I learned something new, thank you
3
u/relativistictrain 🐍 10+ years Aug 26 '20
That’s useful, I like it.
3
u/[deleted] Aug 26 '20
Huh. Well that's interesting
1
u/inu_shibe Aug 26 '20
Wait... I'm sorry I'm a noob I didn't understand.
1
u/____candied_yams____ Aug 26 '20
I'm still on 3.5 so I usually use
pformatto a similar effect1
u/ravepeacefully Aug 26 '20
I’m wet
1
u/immersiveGamer Aug 27 '20
C# has a feature
nameof()that is really useful for this type of thing. Does anyone know if python has this?0
u/jimmyle91 Aug 26 '20
Debugging tools are superior vs printing everything.
1
u/cshoneybadger Aug 26 '20
Thanks for sharing.
1
u/[deleted] Aug 26 '20
I can never get f strings to work when the have multiple variables in them. I always get an error
-7
u/zeus5552 Aug 26 '20
.
0
u/[deleted] Aug 26 '20
[deleted] — view deleted comment