On Mar 19, 2020, at 06:23, Stephen J. Turnbull <turnbull.stephen...@u.tsukuba.ac.jp> wrote: > > Andrew Barnert via Python-ideas writes: > >> [A] context manager seems perfect. It allows you to hint any >> statement, including a loop statement, by adding whatever code you >> want that gets run before and after the statement. > > I wonder: The analogy "decorator : function :: with : suite" seems > useful here. Is it useful in general?
Well, it only goes so far. A decorator is a call to a decorator function: a with statement is construction, entering, and exiting a context manager object. A decorator function is called once, when the function it decorates is defined; a context manager is called every time the statement it manages executes. A decorator function takes the decorated function as its parameter, and the wrapper function it returns gets to see the function’s arguments and its return value; a context manager has no access to the suite it manages or any of the variables it works on. And I think the last one is particularly important here. If you’re thinking of verifying some code by checking that the output bears some relation to the input, a decorator has an obvious place to do that; with a context manager, it’s not even clear what the “input” and “output” of a suite are, but however you define them, you don’t have access to them (barring some tricks you can do with ugly frame hacks). But still, despite the differences, there are some parallels. In particular, if you’re looking to “tag” some code with additional information, decorators and with statements can do that in similar enough ways. Where I think your analogy might be really useful is evaluating the periodic proposals to give context managers access to their managed code or namespace or whatever. Hopefully you or someone else remembers your post next time one of those threads starts. :) _______________________________________________ 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/P2RNUXOQOPQB234AQDJAJDYQJJ7O2ZBO/ Code of Conduct: http://python.org/psf/codeofconduct/