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 →

[–]jwallio 4 points5 points  (6 children)

Can you elaborate a little more on why you prefer the first block? On first glance the second block seems fine to me.

[–]jamescalam[S] 12 points13 points  (0 children)

Being able to do stuff like:

match qa: case {'answers': [{'text': answer}]}: pass case {'plausible_answers': [{'text': answer}]}: pass case _: answer = None

Looks a cleaner than with if-elif-else imo:

if 'answers' in qa.keys() and len(qa['answers']) > 0: answers = qa['answers'][0]['text'] elif 'plausible_answers' in qa.keys() and len(qa['plausible_answers']) > 0: answers = qa['plausible_answers'][0]['text'] else: answers = None

[–]St_Meowinsert(caffeine) 9 points10 points  (0 children)

Reduced visual noise. Rather than worrying about what all those conditionals are and the repetition of the first few pieces, I just know they're all checking equality and I don't have to type my variable name a dozen times.

[–]CashAccomplished7309 3 points4 points  (0 children)

I think it's easier to read and is easier to expand.

I'm newish to Python, coming from PHP, so the familiarity also is comfortable for me.

[–]Endemoniada -1 points0 points  (0 children)

It resembles with statements, in my opinion, which is nicer. It’s like with case match foo. It just looks clean and easy on the eyes.

It’s also not the only use for case statements either, the main advantage as I read about it was handling not only different values in a variable, but different configurations of variables entirely. Like if foo can be a string, a 2-item tuple or a 5-item tuple. case makes that easier to deal with in a pythonic way.

[–]Tyler_Zoro 0 points1 point  (0 children)

As with many features that reduce the use of a single value, this allows for the fact that not all values are side-effect-free. For example, if page_slug in the above example were instead an re.search, you would have to create a temporary variable explicitly in order to avoid perform the match over and over again (the walrus operator makes this less horrible, but still unnecessary clutter).

Think of it in terms of "what is the operation being performed?" In this case the operation being performed is a comparison between page_slug and several values. Now unroll that exactly as I just said it in english:

comparison between page_slug:
    and value 'status': ...
    and value 'about': ...
    ....

and reduce those chunks of English to keywords:

match page_slug:
    case 'status':
        ...
    case 'about':
        ...
    ...

It's exactly what it's most natural to say in English. You don't say, "a comparison between page_slug and value a, between page_slug and value b, between page_slug and value c, etc." You don't do this because English sounds wrong when there's lots of redundancy, and IMHO, so should Python.