简体   繁体   中英

Python: Write function in module to import packages

I am trying to write a function, which is itself loaded, to quickly import a bunch of modules globally.

I thought that, essentially, loaded modules could be treated as variables so I tried:

def loadMods():
    global np
    import numpy as np

and when I loaded numpy (calling np) there was no problem.

What I then did was to create a separate .py file called loadTest containing

# loadTest module
# coding: utf-8

def loadMod():
     global np
     import numpy as np

Then attempted to import numpy using this .py file in python (2.7):

import loadTest
loadTest.loadMod()

but now when attempting calling np I get

File "<stdin>", line 1, in <module>
NameError: name 'np' is not defined

Why does this occur? Any help or alternative ways of doing this would be much appreciated. Thanks a bunch :)

Instead of making a function to do this, why not make another module? You could name it something like modules.py and put all of your imports in there:

import numpy as np
import os
import sys
...

Then, all you need to do is a wildcard import :

from modules import *

and everything will be made available.

You must first define np like that.

In loadTest :

np=None

In somewhere other

import loadTest
loadTest.loadMod()
np=loadTest.np

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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