2

trying to import a specific file called environment.py the issue is that I have this file in more than one location the way i'm loading all my file variables (more than 20 variables in each file) is :

from environment import *

the thing is , I have the environment.py in 2 directories and my sys.path includes both of them. python loads the file from the first location in the list.

Tried

import os, sys, imp
path = os.path.dirname(os.path.abspath(__file__))
file = path + '/environment.py'
foo = imp.load_source('*',file)

But then my variables are loaded into foo and not directly.

Any ideas how to force import * from the right location

2
  • 3
    You can modify sys.path to place the desired directory first before doing the import. Commented Nov 16, 2015 at 17:22
  • This is just one more reason not to use import *. Commented Nov 16, 2015 at 17:35

2 Answers 2

3

If you want to continue with what you started and this is in the global scope, you could add this to the end:

for varName in dir(foo):
    globals()[varName] = getattr(foo, varName)

Now all of the variables that were defined in environment.py are in your global namespace.

Although it's probably easier to just do what Tom Karzes suggested and do:

import os, sys
sys.path.insert(0, path)
from environment import *

# Optional. Probably harmless to leave it in your path.
del sys.path[0]
Sign up to request clarification or add additional context in comments.

1 Comment

The first solution worked, but the second one just imported the wrong environment file. I also tried sys.path.append(path)
0

Put it in a module

/module
    __init__.py
    environment.py

That way you can call

from module.environment import *

And there should be no issue having two modules with environment.py in them, the only difference being the import call. Is that what you mean?

1 Comment

Isn't the module folder actually a python package here? i.e. a module is usually a python file, like environment.py and __init__.py, in this example. Also, you will run into headaches if the package and module have the same name - so environment package with an environment.py module will break import sometimes (or maybe always?). Also, with the latest python versions, if your package is a folder inside another package, you don't need the __init__.py.

Your Answer

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.