I would like to use with for an object that uses __getattr__ to redirect calls.
Howerver, it looks like this is not working with the __enter__ method
Please consider the following simplified code to reproduce the error:
class EnterTest(object): def myenter(self): pass def __exit__(self, type, value, traceback): pass def __getattr__(self, name): if name == '__enter__': return self.myenter enter_obj = EnterTest() print getattr(enter_obj, '__enter__') with enter_obj: pass
Output:
<bound method EnterTest.myenter of <__main__.EnterTest object at 0x00000000021432E8>> Traceback (most recent call last): File "test.py", line 14, in <module> with enter_obj: AttributeError: __enter__
Why doesn't it return to __getattr__ since __enter__ does not exist on the object?
Of course, I could make it work if I just create the __enter__ method and redirect there instead, but I wonder why this is not working.
My python version is as follows:
C:\Python27\python27.exe 2.7 (r27:82525, Jul 4 2010, 07:43:08) [MSC v.1500 64 bit (AMD64)]
source share