Home > Blockchain >  Dynamically assigning module names as aliases
Dynamically assigning module names as aliases

Time:05-04

The code I have down below is from the answer portion of the question Dynamic import: How to import * from module name from variable?

I am able to execute import {module name} but I cannot perform import {module name} as x. How would I be able to modify the importlib function Importer(m_name) so that I can dynamically import a module defined as an alias?

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)
           

Implemented Solution from the selected answer:

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)

CodePudding user response:

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)

just make sure your module_names list elements are tuples by adding that extra comma after math. If you want to make this cleaner, you can require that the length is 2 and put None in cases where you don't want an alias.

  • Related