Python:从导入模块内获取导入模块的详细信息

6 投票
1 回答
3160 浏览
提问于 2025-04-15 17:47

我正在写一段可以重复使用的代码,方便在需要的地方导入,但这段代码需要一些关于导入它的模块的信息。我有一个解决办法,虽然能实现我的需求,但看起来有点丑陋。有没有更好的方法呢?

下面是我正在做的一个简化版本。

我想要的:导入一个方法并使用它,但在mod2中查看f时,它需要一些来自导入模块的信息。

mod1:

from mod2 import f
f(...)

mod2:

from things_i_want import parent_module, importing_module
def f(*args, **kwargs):
    from importing_module.parent_module import models
    # ... do some stuff with it, including populating v with a string

    v = 'some_string'
    m = getattr(importing_module, v, None)
    if callable(m)
        return m(*args, **kwargs)

我丑陋的解决办法:

mod1:

from mod2 import f as _f
def f(*a, **k):return _f(__name__, globals(), *a, **k)
f(...)

mod2:

def f(module_name, globs, *args, **kwargs):
    # find parent modules path
    parent_module_path = module_name.split('.')[0:-1]
    # find models modules path
    models_path = parent_module_path + ['models',]
    # import it
    models = __import__('.'.join(models_path), {}, {}, [''])
    # ... do some stuff with it, including populating v with a string

    v = 'some_string'
    if v in globs:
        return globs[v](*args, **kwargs)

1 个回答

6

这样做不好,因为模块是被缓存的。

举个例子,如果另一个模块,比如说 mod3.py 也导入了 mod2,那么它得到的将是第一次导入时的同一个 mod2 对象。模块不会被重新导入。

也许你在导入 mod2 之前,已经导入了某个其他模块,而那个模块又导入了 mod2,那么这时候你就不是在直接导入 mod2 了。模块只会被导入一次。

所以与其试图找出是谁导入了这个模块,不如使用另一种可重用的方法。也许可以考虑使用类,并传递实例?

撰写回答