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

前端 未结 3 1264
栀梦
栀梦 2021-01-30 01:48

Background:

I have a directory structure like so:

Package/
    setup.py
    src/
        __init__.py
        __main__.py 
        code.py
3条回答
  •  太阳男子
    2021-01-30 02:21

    from code import ......... fails because there is no Python package installed on your system named code. There is a Python module on your system named code, but in your import statement you don't specify the package that your code module can be found in.

    The purpose of the __init__.py file that you have in src/ tells Python that the src/ directory should be treated a Python package, with its contents as the modules within the package. Since code.py is located in src/ along with your __init__.py file, your code module is located in your src package.

    Now that you know which package your code module can be found in, you can import stuff from it with:

    from src.code import .........
    

    Also, as a side note: The __init__.py does its job just by being present in your src/ directory, so it doesn't even need to contain any code. For that reason it's generally a good idea to leave the __init__.py file blank.

提交回复
热议问题