How to configure __main__.py, __init__.py, and setup.py for a basic package setup?

Viewed 23954

Background:

I have a directory structure like so:

Package/
    setup.py
    src/
        __init__.py
        __main__.py 
        code.py

I want to be able to run the code in a lot of different ways.

  1. pip install Package and then python and then from Package import *

  2. python -m Package which should do the thing in __main__.py

  3. python __main__.py which should also do the thing in __main__.py but this time, we assume you've downloaded source rather than pip installing.

Now I've gotten the first two to work, but with a messy setup:

setup.py:

setup(
    name='Package',
    packages=['Package'],
    package_dir={'Package': 'src'},
    ...
    entry_points={ 'console_scripts': ['Package = src.__main__:main' ] }

__init__.py:

from Package.code import .......

__main__.py:

from . import .......

What would make more sense to me would be in both cases to write

from code import ........

but that gives me import errors.

Question:

Is the way I have it really the only way?

And most importantly, how do I support the third use case? Right now, python __main__.py throws

File "__main__.py", line 10, in <module>
    from . import code
ImportError: cannot import name 'class defined in code.py'

Notes:

I have read

3 Answers
Related