1

I have several python modules in the project and I put them in different folders, for example,

pythonProject\folderA\modulex.py
pythonProject\folderB\moduley.py
pythonProject\commonModule\module1.py 

I have __init__.py in each folder. In this situation, how can I import module1 into modulex?

1a1a11a
  • 1,187
  • 2
  • 16
  • 25

3 Answers3

3

Use relatively import

# in modulex
from ..commonModule import module1
LittleQ
  • 1,860
  • 1
  • 12
  • 14
1

Whenever you have python packages (those folders that contain __init__.py files), you can import the modules like below

modulex.py
----------

from pythonproject.commonModule import module1

Try this, If the pythonproject is not defined by the tool, then you could use the relative addressing like below

from ..commonModule import module1
Bharadwaj
  • 737
  • 6
  • 26
  • Thanks for the reply, when I use the first method, it has the following error: `from project.commonModule.Utils import Utils` `ImportError: No module named 'project'` – 1a1a11a Jun 22 '15 at 13:26
  • When I tried to use the second one, it has the following error: `SystemError: Parent module '' not loaded, cannot perform relative import` – 1a1a11a Jun 22 '15 at 13:27
  • For the first one, is there anyway to make the root folder special so that the root folder(project) can be recognized? – 1a1a11a Jun 22 '15 at 13:28
  • Question is how is your project structure? and What IDE do you use – Bharadwaj Jun 22 '15 at 13:32
  • Hey check out the 1st one you tried, you cannot use `from project.commonModule.Utils import Utils` because you are importing utils in utils, try this `from project.commonModule import Utils` – Bharadwaj Jun 22 '15 at 13:33
  • Oh, I have class Utils in module Utils. – 1a1a11a Jun 22 '15 at 13:42
  • The you have to use something like this `from project.commonModule.Utils import Utils as UClass` and then use `UClass.methods()` whenever needed – Bharadwaj Jun 22 '15 at 13:47
  • my project structure is `\project`, `\project\commonModule\module1.py`, `\project\otherFolder\otherModule.py`, and I want to import `module1` into `otherModule`. My IDE is pyCharm – 1a1a11a Jun 22 '15 at 16:00
  • Hey check [this](http://stackoverflow.com/questions/4142151/python-how-to-import-the-class-within-the-same-directory-or-sub-directory) out. Its very similar to your condition – Bharadwaj Jun 22 '15 at 16:42
0

The best if all modules are in the same directory. In case any of them in different possible use of os.chdir(path). With os.chdir(path) method (https://docs.python.org/3.2/library/os.html) possible change working directory in your program.

import os
import modulex

#assume working directory is "pythonProject\folderA\"

os.chdir(r'pythonProject\commonModule\')
#now working directory is "pythonProject\commonModule\"

import module1
mmachine
  • 896
  • 6
  • 10
  • Although this might answer the question, it is always good to include an explanation to the code sample. – BDL Jun 22 '15 at 10:24