Pythonic条件上下文管理

时间:2017-12-09 23:31:02

标签: python

有没有更好的方法来实现这一目标:

if condition:                                                                                                                                      
    with context:                                                                                                       
        do_the_thing()                                                                                                                           
else:                                                                                                                                            
    do_the_thing() 

基本上,在条件的两种情况下,都会做同样的事情,除非如果条件为真,则用特定的上下文完成。

1 个答案:

答案 0 :(得分:0)

可能是这样的,使用工厂方法。

  class BaseContext(object):

       def __enter__(*args, **kwargs):
           return self

       def __exit__(*args, **kwargs):
           return 0

  # Doesn't have to be a class, but for the example
  class ContextFactory(object):

       @staticmethod
       def make(name):
          if not name:
             return BaseContext

          ... other contexts ...

这样,你可以这样做:

  with ContextFactory.make(condition_name):
       do_the_thing()

因此,条件被隐藏在工厂中,并且您的消费代码库不需要就上下文是否必要做出决定。

相关问题