简体   繁体   English

我可以使用 function 在 python 中导入模块吗

[英]Can I import modules in python using a function

I am working on a small library and I need to know can I import modules like numpy, sklearn and etc. Using functions.我正在研究一个小型库,我需要知道是否可以导入 numpy、sklearn 等模块。使用函数。 For example:例如:

def ml():
    import numpy as np
    import pandas as pd
x = np.array([1,2,647,345,3,7,3,8,36,64])

Is this possible?这可能吗? Simply can I import a module using a function and then use that later outside the function The main idea is when the user calls the function ml he has all the modules related to machine learning imported and then he can use them.我可以简单地使用 function 导入一个模块,然后在 function 之外使用它 主要思想是当用户调用 function 时,他可以使用所有相关的模块来机器学习它们。 X = np.array was just kind of an example. X = np.array 只是一个例子。

UPDATED更新

This should work这应该有效

import importlib
def importmd(modulex):
    return importlib.import_module(modulex) #Returning the module
np = importmd("numpy") #Same as import numpy as np

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM