Issue
I am writing a python package that I intend to use for some projects I am working on. I do not want this package to be in a public package index, so I am currently using git submodules
to easily set it up in projects. Every import inside the package is relative.
My package's structure looks like this:
package
|---__init__.py
|---src
|---__init__.py
|---core
|---__init__.py
|---types.py
|---interfaces.py
|---test
I want to make some modules more accessible, so the top level __init__.py
file of my package has some lines like this:
from .src.core import types
from .src.core import interfaces
The problem
I place the python package somewhere in my project:
project
|---__init__.py
|---main.py
|---package
in the main file, i can do the following:
from package import types
def foo(param: types.Foo):
...
but I want to do:
from package.types import Foo # raises ModuleNotFoundError: No module named 'package.types'
I can't find the reason why this happens nor how to solve it. I don't want to publish the package to a public package index and I doubt I can get access to a private one.
Solution
I've gone through python's import system documentation and found out the root of the issue. Altough package.types
is a module, it is not a direct reference to a module, but rather to the types
object from package
. This means that it can only be accessed after package
is explicitly imported.
Knowing this, the solution is quite simple: create a types.py
python file inside package that contains the reexports.
First, add a types.py file in the top level directory of the package:
package
|---__init__.py
|---types.py <-- add this
|---src
|---__init__.py
|---core
|---__init__.py
|---types.py
|---interfaces.py
|---test
Then, the types.py
file imports the types I want to reexport:
from src.core.types import Foo
Now the types can be accessed both ways:
from package import types
def foo(param: types.Foo):
...
from package.types import Foo
def foo(param: Foo):
...
Answered By - Pollastre
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.