fosstodon.org is one of the many independent Mastodon servers you can use to participate in the fediverse.
Fosstodon is an invite only Mastodon instance that is open to those who are interested in technology; particularly free & open source software. If you wish to join, contact us for an invite.

Administered by:

Server stats:

10K
active users

Paul McGuire

I have a code section where I must select one of 4 pyparsing classes based on the settings of 2 arguments - whether to match a string with or without case sensitivity, and as or as not a keyword.

See examples below - I had hoped to make this a poll, but apparently my client will only permit images _or_ polling :( So respond in replies please.

@ptmcg You could also flatten the if method, e.g.

if caseless and asKeyword:
...
elif caseless and not asKeyword:
...
...

In this case I like the declarative flavor of the dict method, and I'd consider wrapping it in a function.

@ptmcg I'd probably put that inside a function and use early return instead of the *else* blocks (to flatten the levels as much as possible).

@ptmcg I think 1 is more readable, but I like the declarative direction you're going with 2. I think 1 would be even more readable with ternary operators (aka conditional expressions), whereas 2 would be more readable if you could find a way to express those caseless/asKeyword notions more semantically in each line. You might also want to do some reading on the Factory pattern on Python if you're not familiar with it, since it was designed for this kind of situation.

@micahellison I could define some throwaway values of True that are semantically relevant (see below).

And thanks for the suggestion about the Factory pattern - I've used it before, but didn't really consider it here. Feel free to look into pyparsing and submit a PR.

@ptmcg If you can assign token and caselessness separately:

condition = is_caseless << 1 | is_keyword
print("caseless" if condition >= 2 else str())
print("keyword" if condition % 2 == 1 else "literal")

(Replace the print statements.)

Otherwise,

if condition == 0:
    print("this is a literal.")
if condition == 1:
    print("this is a keyword.")
if condition == 2:
    print("this is a caseless literal.")
if condition == 3:
    print("this is a caseless keyword.")

@ptmcg I'd use a match statement. However, I presume that's not an option for you as match statements require Python 3.10 or higher?

@guido Thanks for the example! Yes, pyparsing still supports back to Python 3.9, so I can't use match just yet, but this has the advantage of not building the dict just for the sake of doing essentially the same thing. What I like about this and the dict form is that I can review at a glance whether all cases are covered.