0

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 !

2
  • 1
    "Is there a way to do it this way?" Yes, and the way to do it is the way you did it. In other words, your first code block is perfectly valid syntax. (it's a little unusual that you're using & instead of and, and overshadowing the myChain function with a local variable, but both are legal) Commented Oct 17, 2014 at 13:26
  • You are missing the else case in version 2, so any subsequent reference to myChain will refer to the function, not its result (on a related note, don't give them the same name). Commented Oct 17, 2014 at 13:29

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.