Python : How To Call A Global Function From A Imported Module
Would it be possible to call a global function from imported function in Python 3? ./folders/folder1/def.py def do_test(): print('++ def.do_test()') global_function_1() print
Solution 1:
I was able to getmain.py
to work with the following set-up.
(Note I had to add an empty__init__.py
files to both thefolders
andfolder1
subdirectories to get the imports to work.)
File .\class2\folders\folder1\def.py
frommain import global_function_1
def do_test():
print("++ def.do_test()")
global_function_1()
print("-- def.do_test()")
File .\class2\main.py
import importlib
def global_function_1():
print("doing function 1 thing...")
if __name__ == '__main__':
mod = importlib.import_module('folders.folder1.def')
mod.do_test()
Output:
++ def.do_test()
doing function 1 thing...
-- def.do_test()
Solution 2:
What you created is called a module. It can't be used if it's not imported to the file it's used in. In your case, def.py needs to import main.
Importing can be done like this:
from moduleFilename import moduleFunctionname
you can then do
moduleFunctionname()
Alternative:
import moduleFilename
moduleFilename.moduleFunctionname()
EDIT: Seems like Rawing was faster with his comment...
Solution 3:
If you want to keep folders.folder1.def
independent of back-importing stuff, as it seems like something as a library or plugin or such, you can resort to getting it as a callback:
library:
defdo_test(callback):
print("++ def.do_test()")
callback()
print("-- def.do_test()")
main module:
import importlib
def global_function_1():
print("doing function 1 thing...")
mod = importlib.import_module('folders.folder1.def')
mod.do_test(global_function_1)
Post a Comment for "Python : How To Call A Global Function From A Imported Module"