5 ms·
> > The entire import system is broken > What problem are you having with imports? This is a Python function I wrote some years ago to import a module when gi
by DemocracyFTW2 4y ago
> > The entire import system is broken
> What problem are you having with imports?
This is a Python function I wrote some years ago to import a module when given a path:
def module_from_path( name, path ):
### thx to https://stackoverflow.com/a/50395128/7568091 ###
### thx to https://stackoverflow.com/a/67692/7568091 ###
import importlib
import importlib.util
spec = importlib.util.spec_from_file_location( name, path )
module = importlib.util.module_from_spec( spec )
sys.modules[ spec.name ] = module
spec.loader.exec_module( module )
return importlib.import_module( name )
There are so many conspicuous things about it but to put it short, I should be able to just give a relative or absolute file path, call one method, and be done. Damn all those intermediate steps, and why do I have to name it?
- IshKebab 4y agoNice idea, unfortunately it will break all static tooling. IDEs, static type checker, linters, etc. I used to work at a company where they had a custom import system and it was a nightmare.
- mixmastamyk 4y agoWe use it to load classes from the command-line in a pretty big project. That part works perfectly.
- mixmastamyk 4y agoIt 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.