Title: with statement executes type(obj).__exit__ rather than getattr(obj,"__exit__")
Type: behavior Stage:
Components: Library (Lib) Versions: Python 2.7
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: Paul.Wiseman
Priority: normal Keywords:

Created on 2012-09-28 03:02 by Paul.Wiseman, last changed 2012-09-28 03:10 by Paul.Wiseman. This issue is now closed.

Messages (2)
msg171399 - (view) Author: Paul Wiseman (Paul.Wiseman) Date: 2012-09-28 03:02
I found this behaviour today and thought it was weird so asked the question on SO here

basically if I attributes are returned dynamically, they seem to get overlooked by the code that runs the with statements.

>>> class FileHolder(object):
...    def __init__(self,*args,**kwargs):
...        self.f= file(*args,**kwargs)
...    def __getattr__(self,item):
...        return getattr(self.f,item)
>>> a= FileHolder("a","w")
>>> a.write
<built-in method write of file object at 0x018D75F8>
>>> with a as f:
...   print f
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: __exit__
>>> a.__exit__
<built-in method __exit__ of file object at 0x018D75F8>
msg171401 - (view) Author: Paul Wiseman (Paul.Wiseman) Date: 2012-09-28 03:10
I got pointed to an explanation in the docs!

It was confusing, though :)
Date User Action Args
2012-09-28 03:10:23Paul.Wisemansetstatus: open -> closed
resolution: not a bug
messages: + msg171401
2012-09-28 03:02:34Paul.Wisemancreate