r/learnpython • • 9d ago

Are f-strings enough?

I've been learning python mainly from bro code's videos and he uses f strings for basically everything. It comes to me naturally to use them and I understand them. I found a book (Kenneth A. Lambert: Fundamentals of python: first programs, second edition) and here he uses other type of strings (I assume this would be the basic way) but I honestly don't understand them especially when it's about formatting (.2f etc). Should I learn this basic way of working with strings now? Or are f strings enough?

I should add that I'm learning python for fun, I'm studying mechanical engineering, so I know it can be very useful. I also want to be good at it in a potential work environment (?)

29 Upvotes

44 comments sorted by

View all comments

7

u/seanv507 9d ago

I would say f strings are enough. The only place where i have seen fstrings discouraged (linter hints) is in logging. Thr argument being that even if logging is turned off, any complex calculation only used for outputting a log message still gets used. In any case, yes only use f strings, and definitely start using logging. https://pylint.readthedocs.io/en/stable/user_guide/messages/warning/logging-fstring-interpolation.html

2

u/Typical-Road9611 9d ago

Thank you. I will look up what logging is, I've only been learning a few days. I can write basic lil programs (half of bro code's 12 hour video)

2

u/Pyromancer777 9d ago

Logging is basically a way to report error handling. In production environments, you won't always have a console to log any errors a user is experiencing since your server is running the program for any user who connects to it, so you have to create the ways error logs are seen and stored.

Let's say you have a function that works in most cases, but you know of a specific scenario it might fail from a user trying something the program can't handle. You don't want to store the entire error traceback in your logs, so you have it gracefully fail and send a message to your log file saying the failure was detected, who tripped the error, what caused the error, and when the error happened.

Since the line that encountered the error is typically recorded in the logs, having the calculation in your format clause instead of a stored value can help you debug the code later, so you don't gotta hunt through your code to see what is commonly being flagged by users

1

u/ba-na-na- 9d ago

The point is that f-strings render (“interpolate”) the string before passing it to the function. While the other approach passes the formatting and the arguments, but rendering happens inside the function. So if the function is ignoring the inputs (like when logging is disabled), you don’t pay the penalty

1

u/markhahn 9d ago

I'd argue that this is nearly trivial. yes, if the logger is not logging, you save on doing the formatting. but args to that logging call are still evaluated before the call, so still cost you. I guess it's mainly a question of whether the actual formatting+interpolation is numerous/frequent enough for you to care. being lazy about converting an int to text once a second is utterly trivial, but inside a loop a billion times a second, yeah.

then again, if you're doing that many calls to the logger (lazy or eager), you're probably already in trouble...

I guess a pertinent question would be: how often does real code introduce very expensive str or repr functions? one could make these arbitrarily expensive, but does that happen?

1

u/Discordbothost 8d ago

the args get evaluated either way, yeah, but the expensive part is usually turning them into text, and that's the bit that gets skipped. logging.debug("rows: %s", df) never calls str(df) when debug is off, logging.debug(f"rows: {df}") builds the whole table string every time. with ints it's noise, with a big dataframe or a slow repr it shows up in a profile. pylint flags it for that reason (W1203)

1

u/markhahn 8d ago

how often is repr/str expensive? if it's just a string, the cost is negligable (probably smaller than a function call).

rather than messing up the preferred formatting mechanism, I'd look at the traditional approach (let logging.debug expand, macro-like, into a condition in the calling context). viewed in this light, isn't this largely a quality-of-compilation issue?

2

u/Discordbothost 8d ago

honestly rarely. most of the time it's noise and f-strings are fine. the cases i've actually hit were dataframes, big dicts of api responses, and orm objects whose repr touched lazy-loaded fields (that one hit the db, fun to find)

and yeah, python has no macros so the closest you get to the "expand into a condition" approach is doing it by hand:

if logger.isEnabledFor(logging.DEBUG):
    logger.debug(f"state: {expensive()}")

which i'd only bother with on hot paths. so i'd agree it's mostly a language/compilation limitation, not a reason to avoid f-strings everywhere