How can I create imports that always work?

前端 未结 4 1156
孤独总比滥情好
孤独总比滥情好 2021-01-27 23:08

I am struggling a bit to set up a working structure in one of my projects. The problem is, that I have main package and a subpackage in a structure like this (I left out all unn

4条回答
  •  难免孤独
    2021-01-27 23:19

    You should create a structure like this:

    flammi88
    ├── flammi88
    │   ├── __init__.py
    │   ├── code.py
    │   └── mypackage
    │       ├── __init__.py
    │       ├── utils.py
    │       └── work.py
    └── setup.py
    

    then put at least this in the setup.py:

    import setuptools
    from distutils.core import setup
    
    setup(
        name='flammi88',
        packages=['flammi88'],
    )
    

    now, from the directory containing setup.py, run

    pip install -e .
    

    This will make the flammi88 package available in development mode. Now you can say:

    from flammi88.mypackage import utils
    

    everywhere. This is the normal way to develop packages in Python, and it solves all of your relative import problems. That being said, Guido frowns upon standalone scripts in sub-packages. With this structure I would move the tests inside flammi88/tests/... (and run them with e.g. py.test), but some people like to keep the tests next to the code.

    Update:

    an extended setup.py that describes external requirements and creates executables of the sub-packages you want to run can look like:

    import setuptools
    from distutils.core import setup
    
    setup(
        name='flammi88',
        packages=['flammi88'],
        install_requires=[
            'markdown',
        ],
        entry_points={
            'console_scripts': [
                'work = flammi88.mypackage.work:someMethod',
            ]
        }
    )
    

    now, after pip installing your package, you can just type work at the command line.

提交回复
热议问题