You may be interested in this working example of a @namespace decorator
(for functions though, not for classes).

https://stackoverflow.com/a/52358426/791713

—
@namespace
def mynamespace():
eggs = 'spam'
class Bar:
def hello(self):
print("Hello, World!")

assert mynamespace.eggs == 'spam'
mynamespace.Bar().hello()
—


It uses sys.settrace() to find the frame of the function before it is
called to convert it into an actual module object.

My (largely underdeveloped and not recommended to be used) “Node.py”
project implements a preprocessor for Python code in order to implement
such a namespace keyword.


—
namespace Example:
def hello(name):
print('Hello, {}!'.format(name))

Example.hello('World')
—


It does this by converting the code above to the below (and
_NamespaceSyntax__namespace_decorator points to the same namespace
decorator from above)


—
@require._NamespaceSyntax__namespace_decorator
def Example():

def hello(name):
print('Hello, {}!'.format(name))
—


(Link to code here:
https://github.com/nodepy/nodepy/blob/f9e572aa20159af7a1a57b503d0c57693c7a9665/nodepy/extensions.py#L173-L264
)

Personally I like the suggestion by Ricky Teachey to use “def” instead of
introducing a new keyword. If we cannot settle on this kind of syntax
addition, the namespace decorator may be a good addition to the standard
library?

The full code below for reference.


—
import sys
import types


def call_function_get_frame(func, *args, **kwargs):
"""
Calls the function *func* with the specified arguments and keyword
arguments and snatches its local frame before it actually executes.
"""

frame = None
trace = sys.gettrace()
def snatch_locals(_frame, name, arg):
nonlocal frame
if frame is None and name == 'call':
frame = _frame
sys.settrace(trace)
return trace
sys.settrace(snatch_locals)
try:
result = func(*args, **kwargs)
finally:
sys.settrace(trace)
return frame, result


def namespace(func):
frame, result = call_function_get_frame(func)
try:
module = types.ModuleType(func.__name__)
module.__dict__.update(frame.f_locals)
return module
finally:
del frame
—


Best,
-Niklas
_______________________________________________
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/LMC2ECO5K7NXOYZLQKPWRF3SAVFPYBGE/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to