Is there a way in python to store imports inside a module and then run said module to load packages?

Viewed 93

Is there a way I can store my import packages inside a module and then run said module to load the packages? Something like below:

# Store imports in a module
def LoadPackages():
    import pandas as pd
    import numpy as np
    ...

# Run module to load packages
LoadPackages()

I tried this and I got the below error:

d = {'col1': [1, 2], 'col2': [3, 4]}
df = pd.DataFrame(data=d)
df

NameError: name 'pd' is not defined
4 Answers

Declare the variable names as global in the function and the imports will be bound to variable names in the module's global scope.

>>> def LoadPackages():
...     global pd, np
...     import pandas as pd
...     import numpy as np
... 
>>> pd.DataFrame()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'pd' is not defined
>>>
>>>
>>> LoadPackages()
>>> pd.DataFrame
<class 'pandas.core.frame.DataFrame'>
>>> 

You can have another python file called "modules.py" and inside that file you can add

import pandas as pd
import numpy as np

Then in your other python file all you will need to do is import that initial file using

import modules

of course the drawback here is you will always need to call all functions or objects using modules.pd.etc so it would be best to use

from modules import pd, np, #rest of modules

I guess you can just have a file called modules.py, and inside it you put your imports. Then you import it like this in your other files:

from module import *

No, it is only imported if and only if the function is executed. If you may only run a function very rarely and don't need the module imported anywhere else, it may be beneficial to only import it in that function. Or if there is a name clash or other reason you don't want the module or symbols from the module available everywhere, you may only want to import it in a specific function

for example:

def LoadPackages():
    import requests
    res = requests.get("https://google.com")
    print(res)

LoadPackages()

res = requests.get("https://google.com")

Output is:

**<Response [200]>**
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-23-b435c28bc51c> in <module>
      1 LoadPackages()
      2
----> 3 res = requests.get("https://google.com")

NameError: name 'requests' is not defined

Here requests library is imported inside the function scope and successfully performed the "GET" request. And when I made the "GET" request outside function I get the import error.

Related