python动态加载模块_Python:如何从模块动态导入所有方法和属性

1586010002-jmsa.png

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'))

This is roughly equivalent to

import 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 *

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?

解决方案

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})

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值