On 9 June 2018 at 14:46, Jelle Zijlstra <jelle.zijls...@gmail.com> wrote:
> > > 2018-06-08 20:27 GMT-07:00 Alex Walters <tritium-l...@sdamon.com>: > >> Why not... >> >> cool_namespace = SomeNamespaceContextManager() >> >> with cool_namespace: >> def foo(): >> pass >> >> advantage being it introduces no new keyword. The 'disadvantage' is it >> would change semantics of the with statement (as would be required to get >> the names defined in the suite of the context manager) >> >> Actually, this is probably doable now. You can get the globals of the > calling code by doing sys._getframe(), then check which names are added > while the context manager is active. > It's doable without code generation hacks by using class statements instead of with statements. The withdrawn PEP 422 shows how to use a custom metaclass to support a "namespace" keyword argument in the class header that redirects all writes in the body to the given dict: https://www.python.org/dev/peps/pep-0422/#new-ways-of-using-classes https://www.python.org/dev/peps/pep-0422/#extending-a-class even shows how to further use that to extend existing classes with new attributes. We're not likely to actively encourage that approach though - while they do enable some handy things, they also encourage hard to navigate programs with a lot of "action at a distance" side effects that make it tricky to reason locally about the code you're currently looking at (if anything, we've been pushing more in the other direction: encouraging the use of features like checked type hints to better *enable* reasoning locally about a piece of code). Cheers, Nick. -- Nick Coghlan | ncogh...@gmail.com | Brisbane, Australia
_______________________________________________ Python-ideas mailing list Python-ideas@python.org https://mail.python.org/mailman/listinfo/python-ideas Code of Conduct: http://python.org/psf/codeofconduct/