Last active
June 15, 2022 02:59
-
-
Save petarvucetin/023896270b7f7ec9696ef5060dd7d0e4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def my_import(name): | |
mod = __import__(name) | |
components = name.split('.') | |
for comp in components[1:]: | |
mod = getattr(mod, comp) | |
return mod | |
Then you can do: | |
mod = my_import('package.' + name) | |
mod.doSomething() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from importlib import reload # Python 3.4+ | |
import foo | |
while True: | |
# Do some things. | |
if is_changed(foo): | |
foo = reload(foo) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def loadModules(): | |
res = {} | |
import os | |
# check subfolders | |
lst = os.listdir("services") | |
dir = [] | |
for d in lst: | |
s = os.path.abspath("services") + os.sep + d | |
if os.path.isdir(s) and os.path.exists(s + os.sep + "__init__.py"): | |
dir.append(d) | |
# load the modules | |
for d in dir: | |
res[d] = __import__("services." + d, fromlist = ["*"]) | |
return res | |
def getClassByName(module, className): | |
if not module: | |
if className.startswith("services."): | |
className = className.split("services.")[1] | |
l = className.split(".") | |
m = __services__[l[0]] | |
return getClassByName(m, ".".join(l[1:])) | |
elif "." in className: | |
l = className.split(".") | |
m = getattr(module, l[0]) | |
return getClassByName(m, ".".join(l[1:])) | |
else: | |
return getattr(module, className) | |
mods = loadModules() | |
cls = getClassByName(mods["MyModule"], "submodule.filepy.Class") | |
obj = cls() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment