The origin code is(simplify for example):
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from utils.func_a import func_a as _func_a
from utils.func_b import func_b as _func_b
def func_a():
_func_a()
def func_b():
_func_b()
if __name__ == '__main__':
func_a()
now I only called func_a, or maybe func_b, it depends on configuration.
so I want to dynamic do from ... import ..., such as:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def func_a():
_func_a()
def func_b():
_func_b()
if __name__ == '__main__':
keys = ['func_a']
for k in keys:
mod_n = func_n = k
from utils.<mod_n> import <func_n> as _<func_n> # TODO
func_a()
but I don't know to how to implement it?
What I have thought is do import in func_X():
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def func_a():
from utils.func_a import func_a as _func_a
_func_a()
def func_b():
from utils.func_b import func_b as _func_b
_func_b()
if __name__ == '__main__':
func_a()
but this way will do import every time when call function.
Supplement:
I have tried __import__ / importlib, but can't implement this condition
-
2With regards to your last example: imports are cached, so the modules you mention will not be imported every time you call the functions. Read more here.Wander Nauta– Wander Nauta2015年08月11日 09:30:47 +00:00Commented Aug 11, 2015 at 9:30
-
Take a look at the importlib module.PM 2Ring– PM 2Ring2015年08月11日 09:37:09 +00:00Commented Aug 11, 2015 at 9:37
2 Answers 2
__import__ is a builtin function which takes the module name as a string and returns the module as an object. See the documentation:
__import__(name[, globals[, locals[, fromlist[, level]]]])The function imports the module
name, potentially using the givenglobalsandlocalsto determine how to interpret the name in a package context. Thefromlistgives the names of objects or submodules that should be imported from the module given byname.
5 Comments
__import__/importlib, but can't implment this__import__('utils.'+mod_n, fromlist=[func_n])?__import__ doc and found the usage.before I ask the question, I have tried __import__ and importlib, but can't write out the code.
thanks for @machine-yearning, I read the entire doc of __import__.
this is my solution:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
def func_a():
_func_a()
def func_b():
_func_b()
if __name__ == '__main__':
keys = ['func_a']
for k in keys:
mod_n = func_n = k
_temp = __import__('utils.'+mod_n, fromlist=[func_n])
_func = getattr(_temp, func_n)
new_func_n = '_{0}'.format(k)
setattr(sys.modules[__name__], new_func_n, _func)
func_a()