用于布尔评估赋值的Python惯用法

AJ.*_*AJ. 0 python

我有以下C程序作为我希望能在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:~/$ 
Run Code Online (Sandbox Code Playgroud)

在python中,我知道如何做到这一点的唯一方法是:

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.
Run Code Online (Sandbox Code Playgroud)

为什么?因为我想能够说:

if not (x=get_false()): x={}
Run Code Online (Sandbox Code Playgroud)

基本上我正在处理一个错误的API,其中返回的类型是数据可用时的dict,或者是False.是的,一个有效的答案是返回一致的类型,并为故障模式指示器使用Exceptions而不是False.我无法更改底层API,并且我在Python等带动态类型的环境中遇到了这种模式(读取:没有严格的函数/方法接口类型).

有关如何减少if/else开销的任何建议?

nne*_*neo 5

您可以使用

x = get_false() or {}
Run Code Online (Sandbox Code Playgroud)

应该get_false()返回一个False值,Python将返回第二个操作数or.

请参阅Python参考手册的第5.10节.(它至少从那以后就是Python 2.0).