【问题标题】:Import module with the same alias in nested functions in Python在 Python 的嵌套函数中导入具有相同别名的模块
【发布时间】:2021-08-07 23:02:25
【问题描述】:

我注意到了导入的标准方法。

import module as m

我还注意到,可以在函数中导入模块,如下所示。

def someFunction():
    import module as m

    # do some things
    return

我还注意到嵌套函数的作用域使得 内部函数变量具有仅限于该函数的局部作用域

鉴于上述情况,我想(安全地导入两个不同的模块都具有相同的别名,如下所示:在此示例中,这两个模块是test_paramstest_params2,别名(两者通用,但嵌套)是p

import test_params as p

print(p.x)


def some_code():
    import test_params2 as p

    print(p.x)

    return

some_code()

如果 test_params 的 x=100 和 test_params2 的 x=10,那么预期结果将是:

100
10

我测试的时候是什么。

我的问题是:以上内容是否可以接受和理解(pythonic,没有冲突)还是有更好的方法?

【问题讨论】:

  • 请注意,每次调用函数时都会执行导入,这在某些情况下可能不是最佳的。

标签: python import nested-function


【解决方案1】:

参考文档:https://docs.python.org/3/reference/import.html

  • “import 语句结合了两个操作;它搜索命名模块,然后将搜索结果绑定到本地范围内的名称。”
    • 这意味着您不会通过在函数内部添加额外的导入来“污染”您的命名空间,它只会覆盖整个模块。您可以通过引用 test_params 中不在 test_params2 中的东西来测试这一点,在 some_code 中(它不会工作)
    • 但是,每次调用该函数时都会执行导入。这可能是也可能不是问题(取决于性能)。
    • 此外,此方法不够灵活,因为它不允许覆盖(例如,如果存在映射,则覆盖它,但保留未被覆盖的映射)

如果您想为不同的功能指定不同的模块来源映射,允许覆盖(即来自基本模块的默认值),您可以执行以下操作:

import test_params
import test_params2


def module_map(*modules):
    result = {}
    for module in modules:
        new_values = {item:getattr(module, item) for item in dir(module) if not item.startswith("__")}
        result.update(new_values)
    return result

def some_code():
    val_map = module_map(test_params, test_params2)
    print("out2:", val_map)

    return

print("out:", module_map(test_params))
some_code()

测试参数:

y = 8
x = 50
z = 10

test_params2:

y = 200
x = 100

输出:

out: {'x': 50, 'y': 8, 'z': 10}
out2: {'x': 100, 'y': 200, 'z': 10}

【讨论】:

  • 这是重要的部分:“您不会通过在函数内部添加额外的导入来“污染”您的命名空间”。但也注意到其他点。
猜你喜欢
  • 1970-01-01
  • 2020-01-26
  • 2011-06-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-16
  • 2012-01-31
相关资源
最近更新 更多