Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
249 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.

question from:https://stackoverflow.com/questions/65661986/can-i-import-modules-in-python-using-a-function

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

1 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...