[Python-ideas] A "within" keyword

Nick Coghlan ncoghlan at gmail.com
Sat Jun 9 01:07:39 EDT 2018

On 9 June 2018 at 14:46, Jelle Zijlstra <jelle.zijlstra at gmail.com> wrote:

> 2018-06-08 20:27 GMT-07:00 Alex Walters <tritium-list at 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/#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).


Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20180609/5dabdc00/attachment.html>

More information about the Python-ideas mailing list