0

How do I import packages in Python3?

-Package1
|
--InnerPackage1
||
| ---InnerInnerPackage1
| ---InnerInnerPackage2
| ---InnerInnerPackage3
--InnerPackage2
||---InnerInnerPackage4
||---InnerInnerPackage5
||---InnerInnerPackage6
||---InnerInnerPackage7
--InnerPackage3
||---InnerInnerPackage8
||---InnerInnerPackage9
|||
|| ----InnerInnerInnerPackage10
|| ----InnerInnerInnerPackage11
||---InnerInnerPackage12
|||----InnerInnerInnerPackage12
|||----InnerInnerInnerPackage13
|||----InnerInnerInnerPackage14
||---InnerInnerPackge13

Now, let my directory structure be similar to what I've mentioned above, how do I import a package, when my current directory is suppose InnerInnerInnerPackage12, and I have to import InnerInnerPackage6.

Though, when I import, while traversing above using this syntax,

from InnerPackage2 import InnerInnerPackage6

Else, one can also imply importing from the root package

Package1.InnerPackage2.InnerInnerPackage6

Another logic says,

import sys.path
sys.path.insert(0, '%package_directory%\\Package1\\InnerPackage2\\InnerInnerPackage6')

That works in cmd.

Still what would be the correct way to import a module.

It gives an error on running the code in CMD, but when I run the code in JetBrains PyCharm, it works.

Can someone help me out with this problem? Would be grateful! :)

Trishant Pahwa
  • 2,559
  • 2
  • 14
  • 31
  • It seems you are trying to import nested packages. Have you tried using relative imports? Something similar to https://stackoverflow.com/a/2183325/6373131 – Arko Chakraborti Feb 06 '19 at 05:05
  • I get it, but I don't understand the problem if we have to traverse a package that is in a different directory that is a few levels above, the present working directory? – Trishant Pahwa Feb 06 '19 at 05:13

1 Answers1

0

Maybe this is because what we export from python is modules not packages.

I think this issue arises due to that.

Also, to run the same in cmd, one can follow this syntax:

from InnerPackage2.InnerInnerPackage6 import InnerInnerPackage6

This might be the reason, the difficulty arises when we run the same program in both JetBrains PyCharm and on cmd.

Trishant Pahwa
  • 2,559
  • 2
  • 14
  • 31