在python中选择性地导入模块(django)

时间:2013-11-05 03:22:16

标签: python django module

假设我有多个const文件,其中包含常量值。

const/
      const_1.py
      MAX = 10

      const_2.py
      MAX = 100

然后我有3个python包(或django apps)

common_app/
def sum():
    result = 0;
    for i in range(const.MAX):
        result += i
    return i

app_1/
# somehow let common_app to use const_1.py when he's using const                                                                                                                                                                                                            
assert(common_app.sum() == 55)

app_2/
# somehow let common_app to use const_2.py when he's using const                                                                                                                                                                                                            
assert(common_app.sum() == 5050)

因此,当模块导入另一个模块时,我希望导入的模块有选择地导入另一个模块。 这可能吗?

1 个答案:

答案 0 :(得分:0)

您可以使用importlib动态导入。

from importlib import import_module

# modify it to suit your case
statement = True

if statement:
    const = import_module('const_1')
else:
    const = import_module('const_2')