假设def my_function():位于my_apps.views中,我想动态地导入my_function,而不使用类似exec或eval的东西。
有没有来完成这一点。我正在寻找类似于:
my_function = import_func(my_apps.views.my_function)
my_function() ...执行代码
解决方案my_function = getattr(__ import __('my_apps.views'),'my_function')
如果您在编译时碰巧知道函数的名称,可以将其缩短为
my_function = __import __('my_apps.views')。my_functioncode> my_apps.views ,然后将它的 my_function 属性分配给本地 my_function 。
如果您确定只需要一个函数,则可以接受。如果你想要多个属性,你可以这样做:
views = __import __('my_apps.views') my_function = getattr(views,'my_function') my_other_function = getattr(views,'my_other_function') my_attribute = getattr(views,'my_attribute'),因为它更具可读性,并且可以节省一些对 __ import __ 的调用。再次,如果你知道名字,代码可以缩短如上。
你也可以使用 imp 模块,但它更复杂。
Assuming def my_function(): is located in my_apps.views I would like to import "my_function" dynamically without using something like exec or eval.
Is there anyway to accomplish this. I'm looking to do something similar to:
my_function = import_func("my_apps.views.my_function")
my_function() ... code is executed
解决方案you want
my_function = getattr(__import__('my_apps.views'), 'my_function')If you happen to know the name of the function at compile time, you can shorten this to
my_function = __import__('my_apps.views').my_functionThis will load my_apps.views and then assign its my_function attribute to the local my_function.
If you are sure that you only want one function, than this is acceptable. If you want more than one attribute, you can do:
views = __import__('my_apps.views') my_function = getattr(views, 'my_function') my_other_function = getattr(views, 'my_other_function') my_attribute = getattr(views, 'my_attribute')as it is more readable and saves you some calls to __import__. again, if you know the names, the code can be shortened as above.
You could also do this with tools from the imp module but it's more complicated.
更多推荐
我怎样才能动态地导入一个python模块函数?
发布评论