[Python] How to decorate the __enter__ and __exit__ instance methods?

Discussão em 'Python' iniciado por Stack, Abril 9, 2025.

  1. Stack

    Stack Membro Participativo

    I would like to use the decorator deco to reshape the __enter__ and __exit__ instance methods. The code runs but the wrapper is not executed in the with section. Find the actual output below, followed by expected output and finally the code.

    Current output:

    In __init__
    -------------------
    In __enter__
    -------------------
    In wrapper
    Blah, blah, blah
    -------------------
    In __exit__


    Expected output:

    In __init__
    -------------------
    In wrapper
    In __enter__
    -------------------
    In wrapper
    Blah, blah, blah
    -------------------
    In wrapper
    In __exit__


    class contMgr():
    def __init__(self):
    print("In __init__")
    pass

    def __enter__(self):
    print("In __enter__")
    return self

    def __exit__(self, exc_type, exc_val, exc_tb):
    print("In __exit__")
    pass

    def __call__(self, *args, **kwargs):
    print("In __call_")

    def brol():
    print("brol")

    def deco(func):
    def wrapper(*args,**kwargs):
    print("In wrapper")
    result = func(*args, **kwargs)
    return result

    return wrapper

    @Deco
    def test():
    print("Blah, blah, blah")

    mgr = contMgr()
    mgr.__enter__ = deco(mgr.__enter__)
    mgr.__exit__ = deco(mgr.__exit__)
    print("------------------------")
    with mgr:
    print("------------------------")
    test()
    print("------------------------")

    Continue reading...

Compartilhe esta Página