Search code examples
pythondecoratorpython-decoratorscontextmanager

Is using a single class as both a Context Manager and a Decorator frowned upon?


I heard a discussion between 2 developers, one was against having the same object serve both as a context manager and a decorator. His argument was that decorators are meant to enhance\wrap a function, and context managers simply manage data or state when performing an action.

Is there a common agreement\disagreement about this?

I personally like having both options in a single object. Here's a rough example of what I mean:

class Example(object):
    """Context manager AND decorator"""
    def __enter__(self):
        return "Entering"
    
    def __exit__(self, *args, **kwargs):
        return "Exiting"
    
    def __call__(self, func):
        def wrapper(*args, **kwargs):
            with self:
                return func(*args, **kwargs)
        return wrapper

with Example():
    # run something
    some_function()

@Example
def some_function():
    pass


Solution

  • This was more of a debate than a question with an specific answer. Someone mentioned an example from one of the built-in Python modules: https://github.com/python/cpython/blob/3.9/Lib/unittest/mock.py

    I'll accept this as an answer since I was mostly looking for opinions on this. Thanks to those who commented!