简体   繁体   中英

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. It needs some info from the importing module.

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)

My ugly workaround:

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)

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. 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. 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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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