On Nov 18, 2019, at 12:34, Barry <ba...@barrys-emacs.org> wrote: > > Esoteric? I work with files that are open beyond the scope of a single block > of code all the time. Clearly I need to arrange to close the file eventually. > Why would I want the uglyness of __exit__ rather then close()? > I use with all the time if the open() is with linear code.
I think his “esoteric” was a bit strong, but take a step back and think about this: If the normal way to open files gave you a context manager, and you had to “release” the file from it (with a function or method or special syntax or whatever, but something explicit), would that make your code substantially worse? If there were two builtins to open a file, one that gave you a cm and one that didn’t, would that raise the burden of learning and remembering Python too high? What if the second one wasn’t a builtin but had to be imported from io or something? Neither one requires (or even at all encourages) you to manually call __exit__ instead of close, but they solve the same problem (by just putting that __exit__ under the covers where you don’t have to see it, but that’s still a solution). Would either be terrible. And if it would allow us to make context managers easier to combine and reason about, maybe it would be worth it, even if it made some of your code a little more verbose (requiring a release, or an io.open, or whatever)? But I’m not sure we could get there from here in Python. Also, I suspect this wouldn’t really solve the problem. What you really want is something like Rust, where you don’t extract the raw object out of its ownership context, you move it from one ownership context to another—whether that’s a with statement in the caller, or an RAII wrapper around an attribute, or some threaded thingy, or whatever. (You _can_ get the raw file object or pointer to allocated memory or whatever, but you only do that in rare cases, mostly to build new move functions for new context managers.) And I don’t see how to fit that in the with statement design. It’s easy with the “everything is owned by default and every ownership is scoped by default” model that Rust has and C++ vaguely approximates, but with Python you’d need… I’m not sure, but I suspect it would be ugly. _______________________________________________ Python-ideas mailing list -- python-ideas@python.org To unsubscribe send an email to python-ideas-le...@python.org https://mail.python.org/mailman3/lists/python-ideas.python.org/ Message archived at https://mail.python.org/archives/list/python-ideas@python.org/message/F4ZD5G3YMNCD5RWXBFUKWXZ7TUJS2ODW/ Code of Conduct: http://python.org/psf/codeofconduct/