![](/img/trans.png)
[英]Is it possible to get “importing module” in “imported module” in Python?
[英]Python: Get importing module's details from within imported module
我正在編寫一段可重用的代碼來導入我需要它的地方,但它需要一些關於導入它的信息。 我有一個解決方法可以做我想要的,但它有點難看。 有沒有更好的辦法?
這是我正在做的簡化版本。
我想要的:導入一個方法並使用它,但在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)
這是個壞主意,因為模塊是緩存的。
因此,如果另一個模塊,比如mod3.py
,也導入mod2
,它將第一次獲得相同的mod2
對象。 該模塊不會重新導入。
也許你進口的原裝進口一些其他的模塊mod2
導入之前mod2
自己,那么你不是一個進口mod2
了。 模塊只導入一次。
因此,您應該使用另一種可重用的方法,而不是試圖讓誰導入模塊。 也許使用類並傳遞實例?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.