Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: Piping a value through an if/elif statement [duplicate]

I have a function that can return one of three values: a, b, or c.

def f():
    return x # a, b, or c

I need to execute different statements based on the return value of f(): A, B, or C. The best way to do this, that I know of, is:

v = f()
if v == a:
    # Do A
elif v == b:
    # Do B
else:
    # Do C

Without introducing this new variable v, is there a different way to evaluate the return value of f()?
Something like this, maybe?

if f() == a:
    # Do A
elif _value_from_above == b:
    # Do B
else:
    # Do C
like image 741
slybloty Avatar asked Jan 03 '23 01:01

slybloty


1 Answers

Probably not what you want, but one option is to use a dictionary of functions:

def do_a();
    ..
def do_b();
    ..
def do_c();
    ..

strategy = {
    a: do_a,
    b: do_b
    c: do_c
}

strategy[f()]()

But normally you'd want some error handling in case the dictionary entry wasn't found, in which case you'd likely end up with a separate variable anyway, plus you now have to extract each case into its own function.

Maybe even less relevant, if there are only two cases you can use a ternary operator:

do_a() if f() == a else do_b()

Though likely you already know this, plus your question has more than two cases, plus lots of people don't like the ternary operator, but anyway.

If you have a language with a switch statement, like C#/Java/C++ etc, or a pattern matching statement, like any of Haskell/OCaml/F#/Scala/Erlang etc, then you can use those. A pattern matching statement looks like this:

match f() with
| a ->
    // do something
    // and maybe something else too
| b ->
    // do some other thing
    // and yet some other thing

but there is no such feature in Python.

like image 154
junichiro Avatar answered Jan 05 '23 15:01

junichiro