[Python3] file import to another file
3 hours ago, WillLTT said:Because im not really importing a package thats in the default libs.
def packages() recives some variables converts them to imports and then imports that variable.
but i cant put this in main.py as it is:
1. Hella ugly code.
2. I rely on strings or variables from the same file somewhere else in the file
Heres how i convert(split) and import:
def packages(key, key2): import importlib import sys split_ = key.split("/") result_s = split_[0] + "." + split_[1] ext_rm = key2.split(".") globals()[ext_rm[0]] = importlib.import_module('{}.{}'.format(result_s, ext_rm[0]))
Correct me if I'm wrong, but as I understand it the issue is that this code is only importing into the global namespace of importer.py, so you can't access it as "os" from main.py?
Assuming that's the case, I would encourage you not to try that - instead, you should return the imported package from importer.py, then do
os = importer.import("os")
in main.py. You can even set it in the globals for main.py there if you really want os to be available globally within the module.
If you really want to make os available in the global scope of all modules when you run your importer (and once again I advise against this), you can use the builtins module, but to choose the name dynamically at runtime you need to evaluate code at runtime because builtins doesn't support dynamically choosing the name. For example,
import importlib import builtins def do_import(package): exec("builtins.{} = importlib.import_module(package)".format(package))
Here's an interactive demo, but (again) I do not recommend that you do this, there is almost certainly a better way to achieve what you're trying to do:
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now