Python在try b中不带任何参数的yield

2024-09-29 00:15:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在阅读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块中使用它。有人能解释一下这里发生了什么事吗?在


Tags: selffactorydefwithupdateerrorcarcolor
1条回答
网友
1楼 · 发布于 2024-09-29 00:15:27

帖子中的代码似乎有误。如果用contextmanager修饰各种错误处理程序,这是有意义的。注意,在post中,代码导入contextmanager,但没有使用它。这让我觉得此人在创建帖子时犯了一个错误,并将contextmanager从该示例中删除。(postdo使用contextmanager)我认为发布的代码将导致AttributeError,因为各种_error_handler函数不是上下文管理器,没有正确的__enter____exit__方法。在

使用contextmanager,基于the documentation的代码是有意义的:

At the point where the generator yields, the block nested in the with statement is executed. The generator is then resumed after the block is exited. If an unhandled exception occurs in the block, it is reraised inside the generator at the point where the yield occurred.

相关问题 更多 >