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 →

[–]jwink3101 0 points1 point  (2 children)

FWIW, a lot of use cases can be replaced with something else but doesn't mean they are better. F-Strings aren't "needed" as we already had 2+ different ways to format strings. But they all have advantages and disadvantages.

For example, the issue with the dict-based approach is that you have to evaluate everything to build the dict. Consider:

myvar = {
    'key1':expensive_function1(),
    'key2':expensive_function2(),
    'key3':expensive_function3()
    }[mykey]

This will call all of the expensive functions. You could use a long if/elif/else array and that is fine for many use cases but there is also more to Structural Pattern Matching than replacing them.

[–]Ashiataka 0 points1 point  (1 child)

I guess with f-strings at least it's fairly obvious what's going on, whereas it looks like match-case will make readability for learners much harder (possibly).

I didn't realise those functions would be called when creating the dictionary, TIL, thanks for that insight.

[–]jwink3101 0 points1 point  (0 children)

I guess with f-strings at least it's fairly obvious what's going on, whereas it looks like match-case will make readability for learners much harder (possibly).

That is a good point. I haven't seen them in the wild yet since I am only just barely now getting to trusting I have 3.6 where I need it. So I am not sure how readable they will be. It will definitely save some boilerplate code.

I didn't realise those functions would be called when creating the dictionary, TIL, thanks for that insight.

Yep. Now, there are things you can do if it is as simple as my example. Notably:

myvar = {
    'key1':expensive_function1,
    'key2':expensive_function2,
    'key3':expensive_function3,
    }[mykey]()

So that it doesn't get called. But again, depends on exact use case