With class as contextmanager

Terry Reedy 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():
>
> @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?

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)
 >>> c.m()
f called

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__
-9223371924496369383

-- 
Terry Jan Reedy



More information about the Python-list mailing list