[Python-Dev] Fwd: PEP 310(with-syntax): close synonym of __exit__

Samuele Pedroni pedronis at bluewin.ch
Tue Aug 26 03:38:20 EDT 2003

In PEP 310 Reliable Acquisition/Release Pairs:


Open Issues

Should existing classes (for example, file-like objects and locks) gain 
appropriate __enter__ and __exit__ methods?  The obvious reason in favour 
is convenience (no adapter needed).  The argument against is that if 
built-in files have this but (say) StringIO does not, then code that uses 
"with" on a file object can't be reused with a StringIO object.  So 
__exit__ = close becomes a part of the "file-like object" protocol, which 
user-defined classes may need to support.

maybe this is too much DWIMish, but it occurred to me that a further option 
would be for the semantics to be:

var = expr

if hasattr(var, "__enter__"):

   if hasattr(var, "__exit__"):
   elif hasattr(var, "close"): # consider also close as a synonym of __exit__

I'm not proposing to do without __exit__, I recall the next/__next__ 
debate, but I'm wondering if this is well documented, how many times 
considering close a synomym of __exit__ would do the wrong thing, such that 
the user would have to hide close somehow to use 'with' & some object, and 
this wrt the times someone would need a wrapper to have __exit__ trigger a 

I don't think it is worth to have a debate right now, still this should 
maybe be added to the PEP as an option to consider.


More information about the Python-Dev mailing list