我正在阅读this文章,它展示了一段有趣的代码:
class Car(object):
def _factory_error_handler(self):
try:
yield
except FactoryColorError, err:
stacktrace = sys.exc_info()[2]
raise ValidationError(err.message), None, stacktrace
def _create_customizer_error_handler(self, vin):
try:
yield
except CustomizerError, err:
self._factory.remove_car(vin)
stacktrace = sys.exc_info()[2]
raise ValidationError(err.message), None, stacktrace
def _update_customizer_error_handler(self, vin):
try:
yield
except CustomizerError, err:
stacktrace = sys.exc_info()[2]
raise ValidationError(err.message), None, stacktrace
def create(self, color, stereo):
with self._factory_error_handler():
vin = self._factory.make_car(color)
with self._create_customizer_error_handler(vin):
self._customizer.update_car(vin, stereo)
return vin
def update(self, vin, color, stereo):
with self._factory_error_handler():
self._factory.update_car_color(vin, color)
with self._update_customizer_error_handler(vin):
self._customizer.update_car(vin, stereo)
return
在这里,它们在try
块中不带任何参数。然后在with
块中使用它。有人能解释一下这里发生了什么事吗?在
帖子中的代码似乎有误。如果用
contextmanager
修饰各种错误处理程序,这是有意义的。注意,在post中,代码导入contextmanager
,但没有使用它。这让我觉得此人在创建帖子时犯了一个错误,并将contextmanager
从该示例中删除。(postdo使用contextmanager
)我认为发布的代码将导致AttributeError
,因为各种_error_handler
函数不是上下文管理器,没有正确的__enter__
和__exit__
方法。在使用
contextmanager
,基于the documentation的代码是有意义的:相关问题 更多 >
编程相关推荐