Neil
Neil

Reputation: 3291

Python moving modules into sub directory (without breaking existing import structure)

Supposing I am writing library code with a directory structure as follows:

- mylibrary/
|
|-----foo.py
|-----bar.py
|-----baz.py
|-----__init__.py

And to better organise I create a sub directory:

- mylibrary/
|
|-----foobar/
|     |-----foo.py
|     |-----bar.py
|-----baz.py
|-----__init__.py

I want all client code to keep working without updates so I want to update init.py so that imports don't break.

I've tried adding this to init.py:

from foobar import foo

Now if I open a shell I can do:

from mylibrary import foo
print(foo.Foo)

However if I do this:

from mylibrary.foo import Foo

I get No module named mylibrary.foo error. Here is the traceback from my actual example:

Type "help", "copyright", "credits" or "license" for more information.
>>> from global_toolkit import section
>>> section.Section
<class 'global_toolkit.serialization.section.Section'>
>>> from global_toolkit.section import Section
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'global_toolkit.section'
>>> 

Can anyone explain this behaviour?

Upvotes: 0

Views: 690

Answers (1)

Partha Mandal
Partha Mandal

Reputation: 1441

Add this in your __init__.py :

from .foobar import foo, bar
import sys
for i in ['foo','bar']:
  sys.modules['mylib.'+i] = sys.modules['mylib.foobar.'+i]

Now, from mylib.foo import Foo should work.

Upvotes: 3

Related Questions