我可以获取模块别名吗,并且它是全局导入的吗?

时间:2019-01-22 12:46:05

标签: python python-3.x

我有一个模块名称。我想知道:

  1. 是导入的。
  2. 如果是,使用什么别名。

当前,我的解决方案遍历所有模块

import types

def getmodules():
    for name, val in globals().items():
        if isinstance(val, types.ModuleType):
            yield val.__name__, name

result = getmodules()
next(result)

然后,我得到(alias, name)对,我需要迭代直到找到我的模块。

在没有所有显式迭代的情况下有没有办法做到这一点?

Python版本:Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 18:41:36) [MSC v.1900 64 bit (AMD64)] on win32

1 个答案:

答案 0 :(得分:0)

这是您想要的吗?

import types as ty

the_module = 'types'

def getmodule(the_module):
    for name, val in globals().items():
        if isinstance(val, ty.ModuleType):
            if val.__name__ == the_module:
                return name
    return None

alias = getmodule(the_module)
print(f'Module {the_module} ' + (f'imported as {alias}' if alias is not None 
                                 else 'not imported in current scope'))

没有迭代就没有办法,我的意思是即使是成员资格检查也会在后台进行迭代

相关问题