On Fri, Jul 26, 2019 at 10:13:45AM +0300, Batuhan Taskaya wrote:

> I am proposing namespace context managers with implementing `__enter__` and
> `__exit__` on dict objects. It would make closures possible in python with
> a pythonic syntax.

I don't understand what you mean here. Closures are already possible in 
Python with a pythonic syntax.


> a = 4
> namespace = {}
> 
> with namespace:
>     a = 3
> 
> assert a == 4
> assert namespace["a"] == 3


I have long wanted namespaces in Python, but I don't like the above. I 
would prefer to see something like this:

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




Our standard namespace is the module, which is great for 
small libraries and scripts. When your needs are greater (too much code 
to comfortably co-exist in a single file), you can use a package.

But when your needs are lower, and a seperate .py file is too 
heavyweight, we don't have anything convenient for a seperate namespace. 
You can build a module object by hand:

from types import ModuleType
ns = ModuleType("ns")
ns.a = 3

def func():
    return ns.a

ns.func = func


but it's not pretty code, its not convenient, and closures and name 
lookups don't work or look right. You can use a class instead, but again 
closures don't work right, and it is surprising to use a class object 
without instantiating it.

I think a namespace context manager that created and populated a new 
module (or subclass of module) object would fit this use-case nicely.

Use-case summary:

You have a collection of classes, functions and variables which should 
live together in a namespace, seperate from the rest of your classes 
etc, but you don't want to push them out into a seperate .py file.



-- 
Steven
_______________________________________________
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/YUMYJFTWWGUXPCFUFQV2O5AO4UU53X7Y/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to