I am trying to do the following thing :
myChain = myChain(a,b) if a & b else "do_nothing"
Is there a way to do it this way ?
Or should I stick with the usual :
if a & b:
myChain = myChain(a,b)
Thanks !
If you just want a way to do your second code block in a single line, you may delete the newline:
if a & b: myChain = myChain(a,b)
If you absolutely don't want to use an if statement, you could use a conditional expression like you did in your first code block. But this is an unusual way to do it.
myChain = myChain(a,b) if a & b else myChain
I suppose it depends on what you're going for; are you meaning to assign "do_nothing" to myChain? That's what both of these will do. If that's fine, then you're fine -- otherwise, would probably prefer
if a and b:
myNewChain = myChain(a, b) #why assign to the same name as the function/class?
else:
myNewChain = None
...or whatever None should actually be.
If you're using this for flow control -- which it seems like you might be, given the name of the string -- it's typically discouraged to do so, just because people expect to see assignment when there's a ternary operator. Whether or not there's an actual problem with doing it that way, I am admittedly uncertain.
&instead ofand, and overshadowing themyChainfunction with a local variable, but both are legal)elsecase in version 2, so any subsequent reference tomyChainwill refer to the function, not its result (on a related note, don't give them the same name).