0

My directory structure is

app.py
lib
   __init__.py
   _foo.py

Inside __init__.py I have written

from . import _foo as foo

Then inside app.py I try to make a call

from lib.foo import *

but it throws ModuleNotFoundError: No module named 'lib.foo' exception.

Basically I want to import everything from _foo.py, through the __init__.py script. While I realize the code works if _foo.py is renamed into foo.py, I still wonder if there is any way to make import work through __init__.py.

1 Answer 1

1

Not sure about hacking around the import statements, but you could get away with something less explicit like this:

lib/__init__.py

from . import _foo as foo

__all__ = ['foo']

lib/_foo.py

__all__ = [
    'test'
]

test = 1

>>> from lib import *
>>> foo
<module 'lib._foo' from '/path/to/test/lib/_foo.py'>
>>> foo.test
1
>>> 

EDIT: You could achieve something more explicit by updating sys.modules at runtime:

app.py

import sys
from lib import _foo

sys.modules['lib.foo'] = _foo

lib/_foo.py

test = 1

keep lib/__init__.py to make lib a module

After importing app lib.foo will be an available module

>>> import app
>>> from lib import foo
>>> foo
<module 'lib._foo' from '/path/to/test/lib/_foo.py'>
>>> foo.test
1
Sign up to request clarification or add additional context in comments.

1 Comment

Thanka for introducing me to __all__, didn,t know it existed until now :) Though this is somewhat too implicit

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.