Forgive me if this doesn't make sense, but what about a way to make a copy of a function's locals while it is being called?


This can be easily accomplished if you simply return locals() at the end of creating the namespace, but this isn't all that elegant:

def namespace(ns):
    ns_locals = ns()
    from types import ModuleType
    mod = ModuleType(ns.__name__)
    mod.__dict__.update(ns_locals)
    return mod

@namespace
def ns():
    x=1
    y=2
    def f(): ...
    return locals()