Question regarding unexpected behavior in using __enter__ method

aapost aapost at idontexist.club
Thu Apr 20 21:36:18 EDT 2023


On 4/20/23 18:44, Lorenzo Catoni wrote:
> Here, the TypeError occurred because "self" was passed as an input

Instantiate X and observe it there

x2 = X()

 >>> X.__enter__
<class 'int'>
 >>> X.__exit__
<function X.<lambda> at 0x...>
 >>> x2.__enter__
<class 'int'>
 >>> x2.__exit__
<bound method X.<lambda> of <__main__.X object at 0x...>>


To receive self the method must be bound. __enter__ = int doesn't bind 
the int type/class on instantiation, so it never gets self. Your custom 
function binds and receives self.

I am not sure if there is documentation to explain better specifically 
what makes makes type different and not bindable.



More information about the Python-list mailing list