Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
245 views
in Technique[技术] by (71.8m points)

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. 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. X = np.array was just kind of an example.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...