我下面的代碼來自問題動態匯入的答案部分:如何從變數中匯入*從模塊名稱?
我能夠執行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)
uj5u.com熱心網友回復:
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
你不想要別名的情況下。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/470328.html
標籤:Python python-3.x 功能 动态的 模块
上一篇:c_泛型和宏功能