动态分配模块名称作为别名

Dynamically assigning module names as aliases

我下面的代码来自 of the question

我可以执行 import {module name} 但我无法执行 import {module name} as x。我如何才能修改 importlib 函数 Importer(m_name) 以便我可以动态导入定义为别名的模块?

module_names = [('math'), ('numpy','np')]

def Importer(m_name):
    
    m_name = m_name[1] if isinstance(m_name, tuple) else m_name

    module = importlib.import_module(m_name)

    globals().update(
        {n: getattr(module, n) for n in module.__all__} if hasattr(module, '__all__') 
        else 
        {k: v for (k, v) in module.__dict__.items() if not k.startswith('_')
    })

for x in module_names:
    '''
    Works for str ('math')
    Does not work 
    trying to implement import numpy as np
    x[0] = numpy 
    x[1] = as
    '''
    
    Importer(x)
           

根据所选答案实施的解决方案:

import importlib 

module_names = [('math'), ('numpy','np'), ('pandas','pd')]

def Importer(m_name):
    
    module = importlib.import_module(
        m_name[0] if isinstance(m_name, tuple) else m_name
    )

    globals().update(
        {n: getattr(module, n) for n in module.__all__} if hasattr(module, '__all__') 
        else 
        {k: v for (k, v) in module.__dict__.items() if not k.startswith('_')
    })
    
    if isinstance(m_name, tuple):
        globals()[x[1]] = module

for x in module_names:
    
    Importer(x)
import importlib
module_names = [('math',), ('numpy','np')]

def Importer(m_name):
    module = importlib.import_module(m_name[0])
    if len(m_name) > 1:
        globals()[x[1]] = module

for x in module_names:
    Importer(x)

通过在数学后添加额外的逗号来确保您的 module_names 列表元素是元组。如果你想让这个更干净,你可以要求长度为 2 并在你不想要别名的情况下放置 None