我怎样才能动态地导入一个python模块函数?

编程入门 行业动态 更新时间:2024-10-10 10:28:09
本文介绍了我怎样才能动态地导入一个python模块函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

假设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模块函数?

本文发布于:2023-11-29 13:31:50,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   模块   动态   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!