简体   繁体   中英

Python assignment to conditional LHS

I know about

a = val1 if condition else val2

but is there a way to do something like

a if condition else b = val

which throws a SyntaxError (which is understandable I suppose)

I would use a conditional,

if condition:
    a = val
else:
    b = val

but I hate having the same piece of code (here, the right-hand-side) in my program twice (in my real code, val is a non-trivial expression). I know I can just make a dummy variable to hold that piece, but that seems un-idiomatic.

It also occurred to me to do a tuple

ba = (b,a)
ba[bool(condition)] = val
b, a = ba

but that also seems very non-idiomatic.

Is there another way that I'm not thinking of?

No, you can't do that. Make another variable to hold val and use if . Simple is good.

It's doable in one line with tuples:

a,b = val if cond else a, val if not cond else b

But please don't use it, it's ugly and a lot more complicated that a plain if statement.

You can use a function to encapsulate the logic and unpack it back to the variables you're interested in:

def decider(x, y, condition, val):
    if condition:
        return val, y
    return x, val

a, b = decider(a, b, cond, value)

If a and b have some previous values you can simply write:

a, b = (a, val) if condition else (val, b)

Else you can write

a, b = (None, val) if condition else (val, None)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM