Skipping execution of -with- block

前端 未结 7 1989
Happy的楠姐
Happy的楠姐 2020-12-02 17:22

I am defining a context manager class and I would like to be able to skip the block of code without raising an exception if certain conditions are met during instantiation.

7条回答
  •  被撕碎了的回忆
    2020-12-02 18:06

    Context managers are not the right construct for this. You're asking for the body to be executed n times, in this case zero or one. If you look at the general case, n where n >= 0, you end up with a for loop:

    def do_squares(n):
      for i in range(n):
        yield i ** 2
    
    for x in do_squares(3):
      print('square: ', x)
    
    for x in do_squares(0):
      print('this does not print')
    

    In your case, which is more special purpose, and doesn't require binding to the loop variable:

    def should_execute(mode=0):
      if mode == 0:
        yield
    
    for _ in should_execute(0):
      print('this prints')
    
    for _ in should_execute(1):
      print('this does not')
    

提交回复
热议问题