0

Is there a better way of achieving this:

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

Essentially, in both cases of the condition, the same thing is done, except that if the condition is true, it is done with a certain context.

dbrane
  • 887
  • 1
  • 7
  • 19
  • 1
    You can make a context factory. If no context is needed, it will give you a dummy one that doesn't do anything. That way, you won't need to use conditionals throughout your code. – Serguei Fedorov Dec 09 '17 at 23:32
  • You could give your ContextManager an attribute that it checks in its `__enter__` method. So `with context(condition):`, then don't run any of the `__enter__` logic if `condition` is `False`. (A bit hacky!) – Shaun Taylor Dec 09 '17 at 23:38

1 Answers1

0

Possibly something like this, using a factory method.

  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 ...

That way, you can do something like this:

  with ContextFactory.make(condition_name):
       do_the_thing()

Thus, the conditional is buried into the factory, and your consuming code base doesn't need to make decisions on whether a context is necessary, or not.

Serguei Fedorov
  • 7,763
  • 9
  • 63
  • 94