1

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 :)

asked Feb 21, 2015 at 19:53
2
  • All you've done is to make np available inside your loadTest module, which doesn't really help at all. Commented Feb 21, 2015 at 19:55
  • Thats kind of what I was expecting. Thanks for the clarification :) Commented Feb 21, 2015 at 19:58

2 Answers 2

5

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.

answered Feb 21, 2015 at 19:55
Sign up to request clarification or add additional context in comments.

Comments

-1

You must first define np like that.

In loadTest:

np=None

In somewhere other

import loadTest
loadTest.loadMod()
np=loadTest.np
answered Feb 21, 2015 at 19:55

1 Comment

This won't work. Each module's global namespace is separate, and so the global statement in loadMod will only ever write the np name in its own module.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.