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
__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 givenglobals
andlocals
to determine how to interpret the name in a package context. Thefromlist
gives the names of objects or submodules that should be imported from the module given byname
.
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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.