我怎样才能动态地导入一个python模块函数? [英] How can I import a python module function dynamically?
问题描述
假设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_function
code> 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_function
This 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模块函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!