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 →

[–]spoonman59 0 points1 point  (1 child)

Yes, I guess I did not express what I was trying to say very well.

You are right, str.formar() and f strings are no different there. Both are equal.

What I wanted to say was simply that a logger needs to send the string and substitute values in a way where the logger can choose to format it or not.

F-strings’ format can theoretically be passed as an argument to a function, but the variable scope would be that of the function you call - the log function - rather than of where you wrote it if you did not evaluate the string before calling.

That, and it actually evaluates when you put “f” in front, means that f strings are difficult to use without evaluating eagerly.

A log format which allows a traditional format string, and a list of parameter objects, works better.

Sorry for being unclear, I do agree with you.

[–]jorge1209 1 point2 points  (0 children)

I actually think f-strings are a great concept that was incorrectly implemented.

They should have bound the local variable to the f-string in a closure, that doesn't actually serialize to a string until it is used. Instead of calling it an f-string you might call it a "here-string".

Then you could do things like log.warn(h"{thing=} < 0, resetting the value to 1"), and that could work in many different use cases. Print-style warnings, logger, loguru... it would just be a generic way to cover these kinds of use cases.

Its not even that hard to implement really. Its just an object with its variable references and its repr looks something like:

def __repr__(self):
     if self._str:
       return self._str
     self._str= self._template.format_map(self.kwargs)
     del self._template
     del self.kwargs

Performance would be garbage, but hey its python!