With class as contextmanager
tjreedy at udel.edu
Tue Jan 24 21:21:02 EST 2017
On 1/24/2017 4:31 PM, This Wiederkehr wrote:
> having a class definition:
> class Test():
> def __enter__(cls):
> def __exit__(cls, exception_type, execption_value, callback):
> 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:
> But isn't this supposed to be working?
No. Unqualified 'method' means instance method, not class method.
One can simulate instance methods like so:
>>> import types
>>> def f(self): print('f called')
>>> class C: pass
>>> c = C()
>>> c.m = types.MethodType(f, c)
However, this will not work for dunder methods where the lookup for the
method starts with the class and not the object itself.
>>> def h(self): return 1
>>> c.__hash__ = types.MethodType(h, c)
>>> hash(c) # calls type(c).__hash__, not c.__hash__
Terry Jan Reedy
More information about the Python-list