Python importing from parent's child folder

后端 未结 1 857
[愿得一人]
[愿得一人] 2021-01-23 17:24

I have a question. I have a directory setup like this:

folder/
       main.py
       /stuff/
             __init__.py
             function.py
       /items/
            


        
相关标签:
1条回答
  • 2021-01-23 18:14

    Your current directory structure seems ideal, so long as the application is started via main.py.

    Python will always automatically add the parent directory of the main script to the start of sys.path (i.e. folder in your example). This means that the import machinery will give that directory priority when searching for modules and packages that are not part of the standard libarary.

    Given this, you can import the classes.py module into function.py, like so:

    from items import classes
    

    (Note that I have renamed the module, because class is a python keyword).

    If you later added another module to stuff, and wanted to import it into functions.py, you would do:

    from stuff import another
    

    and if a sub-package was added to items, and you wanted to import a module from that, you would do:

    from items.subpackage import module
    

    Imports specified in this top-down way can be used from any module within the application, because they are always relative to the parent directory of the main script, which has priority.

    0 讨论(0)
提交回复
热议问题