>
> a = 4
>
> with Namespace("ns") as ns:
>     a = 3
>     print(a)  # prints "3", not "4"
>
>     def func():
>         return a  # Closes on ns.a, not global a
>
> assert isinstance(ns, types.ModuleType)
> assert ns.name = "ns"
> assert ns.func() == 3
> assert a == 4
>

This is a neat idea and I have wanted something similar myself in
situations I do not want to instantiate class object or break code out to
another module.

Controversial opinion: it may even justify a keyword.  But it wouldn't have
to be a new one, def could work just fine:

def ns:
    a = 3

Food goodly or for badly: something like this would allow one to write code
similar to how you can in javascript (by simply putting it in curly braces
in js), without going to the effort of creating a full fledged class:

def a:
    x = 1
    def b:
        x = 2
    def func():
        return x  # prints 1

print(a.b.x)  # prints 2

Final observation: I think one shortfall in python is that it nudges the
user to use OOP a little bit too forcefully-- especially inexperienced
users, after learning how to write a class the first time. I remember very
well regretting using classes quite a bit too readily in my first couple
years of coding (on year 6 now), when a module would have done much better.
It's true you CAN create a module object and do all of this, but as a
relatively "non expert user" IMO it is very opaque syntax for someone
getting started.
_______________________________________________
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/6HHDIOYGIYLHQGOVE7UAZRCXLR2HGSWT/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to