With class as contextmanager

This Wiederkehr this.wiederkehr at gmail.com
Tue Jan 24 16:31:44 EST 2017


Hellou

having a class definition:

class Test():

@classmethod
def __enter__(cls):
    pass

@classmethod
def __exit__(cls, exception_type, execption_value, callback):
    pass

now using this as a contextmanager does not work, even though Test is an
object and has the two required methods __enter__ and __exit__.

it fails with:
#Attribute Error: __enter__


This is not working because behind the scene it does something like:
type(Test).__enter__(Test)

But isn't this supposed to be working?

I am asking because I'd like to implement the clean up behaviour for
multiple instances directly into the class:

with Test:
    testinstance1 = Test()
    testinstance2 = Test()
# on context exit Test.__exit__ should take care on cleaning up
testinstance1 and testinstance2.


Regards

This



More information about the Python-list mailing list