我想知道是否有任何pythonic或short-form方法来实现以下目标:
error_response = self.check_conditions(request)
# If we have an error response, return it, otherwise continue as normal.
if error_response:
return error_response
类似的东西:
(return self.check_conditions(request)) or pass
或者,函数是否可以返回调用方法,例如:
self.check_conditions(request)
def check_conditions(self, request):
error_response = do_stuff()
if error_response:
return_parent error_response
我觉得第二个概念是打破了大量的编程规则来防止混乱和大灾难,只是一个想法:)
答案 0 :(得分:1)
这很大程度上取决于check_conditions
幕后的内容。您可以将错误处理移到抽象级别并直接处理:
比较
error = False
def foo(request):
global error
try:
result = do_something_with(request)
except SomeWellDefinedError:
error = True
def check_conditions(request):
foo(request)
return error
def main():
error_response = check_conditions(some_request)
if error_response:
# freak out!
使用
def foo(request):
try:
result = do_something_with(request)
except SomeWellDefinedError:
# you can try to handle the error here, or...
raise # uh oh!
def main():
try:
foo(some_request)
except SomeWellDefinedError:
# handle the error here, instead!
答案 1 :(得分:1)
不,条件return
没有简短形式。
但是,要了解问题的第二部分:
Python中有例外。你可以这样写:
class MyErrorResponse(Exception): pass
class MyClass:
...
def check_conditions(self, request):
error_response = do_stuff()
if error_response:
raise MyErrorResponse(error_response)
def do_the_main_stuff():
try:
self.check_conditions()
...
except MyErrorResponse as e:
return e.args[0]