【问题标题】:Pythonic conditional context management [duplicate]Pythonic条件上下文管理[重复]
【发布时间】:2018-05-23 21:05:52
【问题描述】:

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

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

本质上,在这两种情况下,都做了同样的事情,除了如果条件为真,它是在特定的上下文中完成的。

【问题讨论】:

  • 你可以创建一个上下文工厂。如果不需要上下文,它会给你一个不做任何事情的假人。这样,您就不需要在整个代码中使用条件。
  • 你可以给你的 ContextManager 一个属性,它会在 __enter__ 方法中检查它。所以with context(condition):,如果conditionFalse,则不要运行任何__enter__ 逻辑。 (有点hacky!)

标签: python


【解决方案1】:

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

  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()

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多