3 ms·
It is easier in Python 3 than it was. I wrote this and it worked on the first try, although I have some experience with it. The dynamic module: » cat sub
by mixmastamyk 4y ago
It is easier in Python 3 than it was. I wrote this and it worked on the first try, although I have some experience with it.
The dynamic module:
» cat sub/test_module.py
def hello(name):
print(f'Hello {name}')
The main script:
» cat test_script.py
from importlib import import_module
full_module_path = 'sub.test_module' # no ".py"
module = import_module(full_module_path)
# optional, if you want to use across the project:
import sys
sys.modules[full_module_path] = module
print(sys.modules[full_module_path])
# end optional
# try it:
module.hello('there!')
To run it:
» python3 test_script.py
<module 'sub.test_module' from '/home/foo/sub/test_module.py'>
Hello there!
Stack overflow has its uses. But you shouldn't rely on it if things have changed, a lot of their advice is outdated and written by non-experts. The importlib module docs explain this concisely.
https://docs.python.org/3/library/importlib.html#importlib.import_module https://docs.python.org/3/library/importlib.html#importlib.i...
In general, I don't see the intrinsic complexity being reduced much more than this:
from importlib import import_module
module = import_module('sub.test_module')
- DemocracyFTW2 4y agoYeah this was years ago so if that has improved since good for the Python people. > In general, I don't see the intrinsic complexity being reduced much more than this you know in NodeJS I do `const tm = require('sub/test_module');` which I for a number of reasons do find inherently less complex.
- mixmastamyk 4y agoIt's not a builtin in Python-land because importing from a string is exceedingly rare there. I prefer to skip quotes and parens for the 99% case.