Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.


1 Answers

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
like image 184
CopyrightC Avatar answered Nov 21 '25 16:11

CopyrightC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!