Skip to content
Advertisement

How can I import subpackage?

I have a file structure like this:

test.py
Dir1
  __init__.py
  Something.py
  Dir2
    __init__.py
    Something2.py

#Dir1.__init__.py
from .Something import *

Dir2.__init__.py have has the same code, but with .Something2

Something.py has simple add method, Something2.py has simple sub method.

What I need:

#test.py
import Dir1
print(Dir1.Dir2.sub(10, 14))

But I get an error AttributeError: module 'Dir1' has no attribute 'Dir2'.

If I use from .Dir2 import * in Dir1.__init__.py code in test.py works, but also works print(Dir1.sub(10, 14)), what I don’t want. I tryed many variants, but they brought me to error or Dir1.sub working.

This can probably be found on the Internet, but my knowledge of English is suffering and I may miss the answer. Of course I’ve already tried searching for it on the Internet.

I will be very grateful for your answer.

Advertisement

Answer

Probably it is crutch, but I found solve. Now I have this file structure:

test.py
Dir1
  __init__.py
  Dir1
    __init__.py
    Something.py
    Dir2
      __init__.py
      Something2.py

#Dir1.__init__
import Dir1 as Add
from .Dir1 import Dir2 as Sub

And now I can use

#test.py
import Dir1
print(Dir1.Sub.sub(10, 7))

And can’t use

#test.py
import Dir1
print(Dir1.sub(10, 7))

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement