Dawid Żurawski
Dawid Żurawski

Reputation: 579

Setuptools python - import problem inside project

I'm trying to build simple project and then prepare it to create whl file. But after pip install <name>.whl I have strange import problem. Project structure:

foo/
    /foo
        __init__.py
        main.py
        bar.py
    setup.py

setup.py file:

from setuptools import setup, find_packages

setup(
    name='foo',
    version='0.0.1',
    packages=find_packages(),
    include_package_data=True,
    entry_points={'console_scripts': ['foo=foo.main:func1']}
)

main.py

from bar import func2

def func1():
    print('func1')
    func2()

bar.py

def func2():
    print('func2')

I have an empty init file.

I create whl file by command: python3 setup.py bdist_wheel and then cd dist/ && pip install ...

But when I run script by foo I got an error:

ModuleNotFoundError: No module named 'bar'

This problem exists only when I have splited project in a few files, when I tried to keep everything in main.py (removed bar.py) without imports then it worked.

Any idea how should I modify setup.py?

Upvotes: 2

Views: 1383

Answers (1)

mgilson
mgilson

Reputation: 310187

The problem is with your imports -- not your setup.py. What is happening is that your setup.py is installing the package foo which has submodules main and bar.

To import a function from a submodule, you do something like:

from foo.bar import func2

or, if you are doing a package relative import (e.g. importing bar from main):

from .bar import func2

This second version won't work if the module that is doing the importing isn't part of the foo package.

Upvotes: 1

Related Questions