Pythonで実行できるようにしたいことの例として、次のCプログラムがあります。
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:~/$
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.
なんで?私が言うことができるようにしたいので:
if not (x=get_false()): x={}
基本的に、返される型がデータが利用可能な場合のdictまたはFalseのいずれかである不正なAPIを回避しています。はい、有効な答えは、一貫性のあるタイプを返し、障害モードインジケータにFalseではなくExceptionsを使用することです。ただし、基盤となるAPIを変更することはできません。また、動的型付けを使用するPythonなどの環境でこのパターンにかなり遭遇します(関数/メソッドインターフェイスの厳密な型付けなしで読んでください)。
if / elseオーバーヘッドを減らす方法について何か提案はありますか?