On 20/11/2019 01:57, Oscar Benjamin wrote:
On Tue, 19 Nov 2019 at 12:03, Paul Moore firstname.lastname@example.org wrote:
On Tue, 19 Nov 2019 at 11:34, Oscar Benjamin email@example.com wrote:
If I was to propose anything here it would not be to disallow anything that you can currently do with context managers. Rather the suggestion would be to:
- Clearly define what a well-behaved context manager is.
- Add convenient utilities for working with well behaved context managers.
- Add well-behaved alternatives for open and maybe others.
- Add Random832's utility for adapting misbehaving context managers.
That sounds reasonable, with one proviso. I would *strongly* object to calling context managers that conform to the new expectations "well behaved", and by contrast implying that those that don't are somehow "misbehaving". File objects have been considered as perfectly acceptable context managers since the first introduction of context managers (so have locks, and zipfile objects, which might also fall foul of the new requirements). Suddenly deeming them as "misbehaving" is unreasonable.
Perhaps a less emotive way of distinguishing these classes of context managers would be as "eager" vs "lazy". An eager context manager jumps the gun and does whatever needs undoing or following up before its __enter__ method is called. A lazy context manager waits until __enter__ is called before committing itself.
I don't really want to give a sense of equality between eager and lazy though. To me it is clear that lazy context managers are preferable.
As context managers, yes, lazy managers make chaining them easier because there's no mess to clean up if the chain breaks while you are creating it. On the other hand, eager managers like open() can be used outside a "with" statement and still manage resources perfectly well for a lot of cases. It a matter of fitness for different purposes, so even "preferable" is a relative term here.