简体   繁体   English

Python:从导入的模块中导入模块的详细信息

[英]Python: Get importing module's details from within imported module

I'm writing a piece of reusable code to import where I need it, but it needs some info about what is importing it. 我正在编写一段可重用的代码来导入我需要它的地方,但它需要一些关于导入它的信息。 I have a workaround that does what I want, but it's a bit ugly. 我有一个解决方法可以做我想要的,但它有点难看。 Is there a better way? 有没有更好的办法?

Here is a simplified version of what I'm doing. 这是我正在做的简化版本。

What I want: Import a method and use it, but look at f in mod2. 我想要的:导入一个方法并使用它,但在mod2中查看f。 It needs some info from the importing module. 它需要导入模块的一些信息。

mod1: MOD1:

from mod2 import f
f(...)

mod2: 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)

My ugly workaround: 我丑陋的解决方法:

mod1: MOD1:

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

mod2: 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)

That's a bad idea, because modules are cached. 这是个坏主意,因为模块是缓存的。

So if another module, say, mod3.py , also imports mod2 , it will get the same mod2 object of the first time. 因此,如果另一个模块,比如mod3.py ,也导入mod2 ,它将第一次获得相同的mod2对象。 The module is not reimported. 该模块不会重新导入。

Maybe you imported some other module that imported mod2 before importing mod2 yourself, then you're not the one importing mod2 anymore. 也许你进口的原装进口一些其他的模块mod2导入之前mod2自己,那么你不是一个进口mod2了。 Modules are imported only once. 模块只导入一次。

So instead of trying to get who imported the module, you should use another, reusable approach. 因此,您应该使用另一种可重用的方法,而不是试图让谁导入模块。 Perhaps using classes and passing the instance around? 也许使用类并传递实例?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM