I have the following C program as an example of what I would like to be able to do in python:
foo@foo:~/$ cat test.c
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
bool get_false(){
return false;
}
bool get_true(){
return true;
}
void main(int argc, char* argv[]){
bool x, y;
if ( x = get_false() ){
printf("Whiskey. Tango. Foxtrot.\n");
}
if ( y = get_true() ){
printf("Nothing to see here, keep moving.\n");
}
}
foo@foo:~/$ gcc test.c -o test
test.c: In function ‘main’:
test.c:13: warning: return type of ‘main’ is not ‘int’
foo@foo:~/$ ./test
Nothing to see here, keep moving.
foo@foo:~/$
In python, the only way I know how to do this is:
foo@foo:~/$ cat test.py
def get_false():
return False
def get_true():
return True
if __name__ == '__main__':
x = get_false()
if x:
print "Whiskey. Tango. Foxtrot."
y = get_true()
if y:
print "Nothing to see here, keep moving."
#if (z = get_false()):
# print "Uncommenting this will give me a syntax error."
#if (a = get_false()) == False:
# print "This doesn't work either...also invalid syntax."
foo@foo:~/$ python test.py
Nothing to see here, keep moving.
Why? Because I’d like to be able to say:
if not (x=get_false()): x={}
Basically I’m working around a bad API where the type returned is either a dict when data is available, or False. Yes, a valid answer would be to return consistent types and to use Exceptions instead of False for a failure mode indicator. I can’t change the underlying API though, and I run into this pattern quite a bit in environments like Python with dynamic typing (read: without strict typing for function/method interfaces).
Any suggestions on how to reduce the if/else overhead?
You can use
Should
get_false()return aFalsevalue, Python will return the second operand ofor.See section 5.10 of the Python reference manual. (It’s been there since at least Python 2.0).