代码之家  ›  专栏  ›  技术社区  ›  Jake

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

  •  4
  • Jake  · 技术社区  · 15 年前

    我想要的是:

    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(...)
    

    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 回复  |  直到 15 年前
        1
  •  6
  •   nosklo    15 年前

    这是个坏主意,因为模块是缓存的。

    mod3.py ,也进口 mod2 mod2

    也许你导入了其他导入的模块 进口前 mod2 你自己,那么你不是那个进口的人

    因此,您应该使用另一种可重用的方法,而不是试图找出是谁导入了模块。也许使用类并传递实例?