On 11/19/19 8:57 PM, 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. You say it's unreasonable to claim now that some long-existing context managers are "misbehaving". Perhaps there is a better word but an alternative that implies that all existing context managers are "perfectly acceptable" will not convey the useful point that some ways of doing things are better than others.
If I understand it right, an eager context manager (like open currently is) allows itself to be used somewhat optionally, and not need to be in a with statement. A lazy context manager on the other hand, seems to be assuming that it will be used in a with statement (or something similar), as it is putting off some important work until it sees it is in there.
It impetus for this seems to be to make a cleaner syntax for a with statement managing multiple resources through context managers, if we only need simple recovery (the built in provided by the context manager). It may be at the cost of making more complex (and explicit) handling of conditions for current (or possible future) 'eager' managers. For example, if open doesn't actually open the file, but only prepares to open, then the use of a file outside a with becomes more complicated if we want somewhat precise control over the file.