Python:如何从模块动态导入所有方法和属性 [英] Python: How to import all methods and attributes from a module dynamically

查看:251
本文介绍了Python:如何从模块动态导入所有方法和属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想动态加载模块,给定模块的字符串名称(来自环境变量).我正在使用Python 2.7.我知道我可以做类似的事情:

I'd like to load a module dynamically, given its string name (from an environment variable). I'm using Python 2.7. I know I can do something like:

import os, importlib
my_module = importlib.import_module(os.environ.get('SETTINGS_MODULE'))

这大致等于

import my_settings

(其中SETTINGS_MODULE = 'my_settings').问题是,我需要等同于

(where SETTINGS_MODULE = 'my_settings'). The problem is, I need something equivalent to

from my_settings import *

因为我希望能够访问模块中的所有方法和变量.我已经尝试过

since I'd like to be able to access all methods and variables in the module. I've tried

import os, importlib
my_module = importlib.import_module(os.environ.get('SETTINGS_MODULE'))
from my_module import *

但是我在执行此操作时遇到了很多错误.有没有一种方法可以在Python 2.7中动态导入模块的所有方法和属性?

but I get a bunch of errors doing that. Is there a way to import all methods and attributes of a module dynamically in Python 2.7?

推荐答案

如果您有模块对象,则可以模仿import *使用的逻辑,如下所示:

If you have your module object, you can mimic the logic import * uses as follows:

module_dict = my_module.__dict__
try:
    to_import = my_module.__all__
except AttributeError:
    to_import = [name for name in module_dict if not name.startswith('_')]
globals().update({name: module_dict[name] for name in to_import})

但是,这几乎肯定是一个非常糟糕的主意.您将毫不客气地踩着任何具有相同名称的现有变量.正常使用from blah import *时,这已经够糟糕的了,但是当您动态执行from blah import *时,关于哪些名称可能会冲突的不确定性更大.最好只导入my_module,然后使用常规属性访问(例如,my_module.someAttr)从中访问所需的内容,如果需要动态访问其属性,则最好使用getattr.

However, this is almost certainly a really bad idea. You will unceremoniously stomp on any existing variables with the same names. This is bad enough when you do from blah import * normally, but when you do it dynamically there is even more uncertainty about what names might collide. You are better off just importing my_module and then accessing what you need from it using regular attribute access (e.g., my_module.someAttr), or getattr if you need to access its attributes dynamically.

这篇关于Python:如何从模块动态导入所有方法和属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆