I have no idea if this is a good idea, but Python already has modules to be
namespaces for a collection of functions and values.
And while a class decorator is *supposed* to return a class, it can, in
fact, return anything. So you can make a decorator that converts a class
definition to a module object:
In [47]: def make_mod(cls):
...: mod = imp.new_module(cls.__name__)
...: for name, attr in vars(cls).items():
...: if not name.startswith("_"):
...: setattr(mod, name, attr)
...: return mod
...:
In [48]: @make_mod
...: class Fake:
...: an_attribute = "this"
...: def a_function(a,b):
...: print("a_function:", a, b)
...:
In [49]: Fake.an_attribute
Out[49]: 'this'
In [50]: Fake.a_function(3, 4)
a_function: 3 4
In [51]: type(Fake)
Out[51]: module
In [52]: vars(Fake)
Out[52]:
{'__name__': 'Fake',
'__doc__': None,
'__package__': None,
'__loader__': None,
'__spec__': None,
'an_attribute': 'this',
'a_function': <function __main__.Fake.a_function(a, b)>}
I expect this will give your functions a very odd globals() though ;-)
But this made me think -- we already have modules, so if we do want a
"namespace" type of some sort, why not simply have syntax for making a
module inline:
new_module:
def this():
pass
x = 4
It would be kind of nice to be able to make anew module without having to
have an actual file (or fake one)
-CHB
-CHB
On Tue, Oct 6, 2020 at 11:02 PM Greg Ewing <[email protected]>
wrote:
> On 7/10/20 2:45 pm, Random832 wrote:
> > I think the feature should allow for the functions to directly access
> > each other from the namespace's scope without requiring an attribute
> > lookup.
>
> That got me thinking, and I came up with this:
>
> def submodule(f):
> return type(f.__name__, (), f())
>
> @submodule
> def Stuff():
>
> def f1():
> print("First function")
> f2()
>
> def f2():
> print("Second function")
>
> return locals()
>
> Stuff.f1()
>
> The only ugly part is the need for the 'return locals()', but that could
> probably be alleviated with a bit of bytecode hacking.
>
> --
> Greg
> _______________________________________________
> Python-ideas mailing list -- [email protected]
> To unsubscribe send an email to [email protected]
> https://mail.python.org/mailman3/lists/python-ideas.python.org/
> Message archived at
> https://mail.python.org/archives/list/[email protected]/message/KCUWQDLCNUHAP47DR7L3AJPBPI6H64LM/
> Code of Conduct: http://python.org/psf/codeofconduct/
>
--
Christopher Barker, PhD
Python Language Consulting
- Teaching
- Scientific Software Development
- Desktop GUI and Web Development
- wxPython, numpy, scipy, Cython
_______________________________________________
Python-ideas mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at
https://mail.python.org/archives/list/[email protected]/message/CAV5DQHBWRFMVCHZI2CFLR5BDUMUXOYC/
Code of Conduct: http://python.org/psf/codeofconduct/