Issue2135

classification
Title: with statement should support AutoCloseable objects
Type: rfe Severity: normal
Components: Versions: Jython 2.7
Milestone:
process
Status: open Resolution: remind
Dependencies: Superseder:
Assigned To: zyasoft Nosy List: jeff.allen, zyasoft
Priority: normal Keywords:

Created on 2014-05-04.21:23:42 by zyasoft, last changed 2014-09-26.05:17:53 by zyasoft.

Messages
msg8336 (view) Author: Jim Baker (zyasoft) Date: 2014-05-04.21:23:41
Java objects that implement both AutoCloseable and Closeable should automatically be closed by the with statement.

Per the docs of AutoCloseable, "implementers of this interface are strongly encouraged to make their close methods idempotent". However this can be guaranteed by also testing for implementing Closeable, given that idempotence is in fact guaranteed: "If the stream is already closed then invoking this method has no effect." (ttp://docs.oracle.com/javase/7/docs/api/java/io/Closeable.html#close()
msg8459 (view) Author: Jim Baker (zyasoft) Date: 2014-05-21.20:31:55
Target beta 4
msg8778 (view) Author: Jim Baker (zyasoft) Date: 2014-06-20.20:51:25
More thoughts:

1. Use org.python.core.ContextManager support to help with inlining of code, vs just the simple approach of adding __enter__ and __exit__ in PyJavaType.

2. Should also support resources that are not AutoCloseable, but could be if there wasn't an issue with checked exceptions, especially InterruptibleException. So in particular, there's this requirement for AutoCloseable:

> Implementers of this interface are also strongly advised to not have the close method throw InterruptedException. This exception interacts with a thread's interrupted status, and runtime misbehavior is likely to occur if an InterruptedException is suppressed. More generally, if it would cause problems for an exception to be suppressed, the AutoCloseable.close method should not throw it.

However, this is not an issue for Jython - we don't need to suppress such exceptions. In particular, this means that we can also support java.util.concurrent.lock.Lock such that __enter__ calls lockInterruptibly;__exit__ calls release. During the Java 7 PEP cycle on try-with-resource it was realized this could not be done with Java, but no issues again with Jython.
msg8788 (view) Author: Jeff Allen (jeff.allen) Date: 2014-06-22.20:19:35
This seems a very useful idea. Did you also notice this thread on Python-dev, including mention of idempotence of close() for Python IOBase derivatives? I think we achived that in _io ... ISTR I had difficulty getting close and flush arranged correctly.
History
Date User Action Args
2014-09-26 05:17:53zyasoftsetresolution: remind
2014-06-22 20:19:35jeff.allensetnosy: + jeff.allen
messages: + msg8788
2014-06-20 20:51:26zyasoftsetmessages: + msg8778
2014-05-21 20:31:55zyasoftsetmessages: + msg8459
2014-05-04 21:23:42zyasoftcreate