On Tue, 19 Nov 2019 at 11:34, Oscar Benjamin
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: 1. Clearly define what a well-behaved context manager is. 2. Add convenient utilities for working with well behaved context managers. 3. Add well-behaved alternatives for open and maybe others. 4. 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. A new name should be chosen, which *doesn't* have the implication that these are somehow "better" than traditional context managers. Maybe "resource containers", although as you point out above, resources probably aren't the key point here. Naming is hard, and I'll leave it up to you ;-)
The point is not that anything should be disallowed but that we can have useful context manager utilities if we have a clear understanding of how to use them and easy ways to use them correctly. Then if someone hits up against a bug from using a misbehaving context manager where they shouldn't the response can be "change the context manager or don't use it in that situation" rather than "that's a bug in the useful utilities so let's remove those".
Again, you're characterising things as "misbehaving". Rather I'd say that the *user* is at fault for attempting to use a context manager that doesn't satisfy the (additional) requirements imposed by the utility. The fix is to use something that *does* satisfy the utility's requirements (which may mean using a different object, or wrapping the context manager, or whatever). The tricky bit here is the human problem of making it clear to people what the additional constraints are, and how to tell what satisfies them - that was the original problem with nested, that it *didn't* do a good job of making it obvious that you needed to use opened() with it rather than open() (more accurately, I guess, that you had to use an "open file container" object, not a raw file object). Paul