On Nov 20, 2019, at 7:50 AM, Rhodri James email@example.com wrote:
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.
-- Rhodri James *-* Kynesim Ltd _______________________________________________
To my mind, eager context managers nest just fine, if you put each into their own context. What it seems the lazy managers let you do is squish multiple context managers into a single context, but then you get the question of which of them actually is providing the context that you are in?