聽起來好像你想要的東西像..
if result = some_function(arg1, arg2):
return result
這在Python中是非常故意不可能的。編寫if a = b
而不是if a == b
的錯字太常見了,並且允許將這種分配與流量控制混合在一起。如果這是必要的,它分成兩行:
x = some_function()
if x:
print "Function returned True"
這方面的一個更實際的例子是..
result = re.match("a", "b")
if result:
print result.groups()
(更正確,你應該在這種情況下做if result is not None:
,雖然上述作品)
在您的具體情況(「驗證我的內部函數成功返回」),這聽起來像你應該使用異常。如果一切都很好,只要返回你想要的東西。如果事情變得糟糕,請舉例說明。
異常在Python並不像很多其他語言 - 例如,他們在內部使用流控制(如StopIteration除外)
我會考慮以下遠更Python比使用的返回碼:
#!/usr/bin/env python2.6
def some_function(arg1, arg2):
if arg1 + arg2 > 5:
return "some data for you"
else:
raise ValueError("Could not complete, arg1+arg2 was too small")
然後,你可以調用函數在單行:
return some_function(3, 2)
這要麼返回值,或將引發異常,這你可以處理這個異常敏感的地方:
def main():
try:
result = some_function(3, 5)
except ValueError, errormsg:
print errormsg
sys.exit(1)
else:
print "Everything is perfect, the result was {0}".format(result)
或者,如果這種情況下,實際上是一個錯誤,乾脆讓停止一個不錯的堆棧跟蹤的應用程序。
是的,它比一行更長,但Python背後的想法是簡潔,但明確和可讀性。
基本上,如果函數不能再繼續,引發異常。處理這個異常要麼在那裏你可以從問題中恢復,或者用一個錯誤信息呈現給用戶.. 除非你正在寫一個庫,在這種情況下離開異常堆棧運行到調用代碼
或者,在詩的形式:
$ python -m this
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
最後,它可能是值得一讀了"PEP 8",風格指南爲Python。它可能會回答你的一些問題,比如「如果陳述'pythonic'是單線嗎?」
複合語句(同一行上的多個語句)通常是不鼓勵的。
是:
if foo == 'blah':
do_blah_thing()
do_one()
do_two()
do_three()
而不是:
if foo == 'blah': do_blah_thing()
do_one(); do_two(); do_three()
似乎很濃縮了我。實際上太多了,我認爲錯誤放棄應該放在它自己的路線上。 – 2009-10-09 15:14:00
夠公平的。如果陳述'pythonic'是單線嗎?通常這種語言會讓你使用'pythonic'語法,但它確實可以使用這種語法。 – cgyDeveloper 2009-10-09 15:33:23
單行'if'語句不鼓勵,請參閱Python風格指南,PEP8 http://www.python.org/dev/peps/pep-0008/ – dbr 2009-10-09 16:33:12