2

e.g. pictures this:

def some_operation(var) -> (bool, String):
    return False, "This is a test"


success, error_message = someOperation("aVar")
if not success:
    print(error_message)

I feel there must be a way to do something in one line that prints msg if err == false. If there were defined you could do

`success or print(error_message)`

Maybe some sort of wrapper or lambda helper to take the method call that returns the two element tuple?

Mitchell Currie
  • 2,769
  • 3
  • 20
  • 26

2 Answers2

2

It's best practice to use what you're using right now, but anyway, this is Python, a.k.a home of the one-liners (actually, it has second place after APL)...

(lambda success, error_message: None if success else print(error_message))(*someOperation("aVar"))
3442
  • 8,248
  • 2
  • 19
  • 41
  • You're right, this is closest to what I was after although @Paul effort is good too, this squashes output if it's empty. I should more effort int the surround functions than make it one line. – Mitchell Currie Mar 21 '16 at 05:27
0

Not really good practice, but this comes close to what you want:

print ''.join((not success)*message for success,message in [fn()])

To test it out:

retGood = lambda: (True, "that was good")
retBad = lambda: (False, "that was not so good")

print 'Success -> ' + ''.join((not success)*message for success,message in [retGood()])
print 'Failure -> ' + ''.join((not success)*message for success,message in [retBad()])

Prints:

Success -> 
Failure -> that was not so good

It is not quite what you asked for, as it does print a blank line if success is returned as True. But it is a one-liner to print the error message only if a False success is returned.

PaulMcG
  • 62,419
  • 16
  • 94
  • 130