15 ms·
Thanks. I wonder what it would be like if Python had syntax for modules instead of them being tied to separate files. I would prefer being able to create this c
by da39a3ee 3y ago
Thanks. I wonder what it would be like if Python had syntax for modules instead of them being tied to separate files. I would prefer being able to create this container in the same file as other code.
- Spivak 3y agoSay no more! Python? Rules? Unheard of. from importlib.machinery import ModuleSpec import importlib.util import sys spec = ModuleSpec("mymodule", loader=None) module = importlib.util.module_from_spec(spec) module.__dict__.update({"a": 42}) sys.modules["mymodule"] = module import mymodule print(mymodule.a) # -> 42 That's if you want a proper module. But modules can be any type and it's officially supported! import sys from types import SimpleNamespace sys.modules["mymodule"] = SimpleNamespace(b=37) import mymodule print(mymodule.b) # -> 37 # ^^^ This is literally just calling __getattr__ on the module object. Do with that what you will. This will cross files as well but you need to make sure the code to create the module runs before you try importing it! glhf
- da39a3ee 3y agoThanks! This was a great answer. > Python? Rules? Unheard of. OK, since it's Christmas, I'd like to be able to write Module MyModule a = 42 b = 37
- Spivak 3y agoI think I can do that. import sys class DataModule: def __init_subclass__(cls): sys.modules[cls.__name__.lower()] = cls class MyModle(DataModule): a = 42 b = 37 import mymodule mymodule.a == 42 Or as a class decorator def datamodule(cls): sys.modules[cls.__name.__.lower()] = cls @datamodule class MyModule: a = 42 import mymodule mymodule.a = 42