简体   繁体   中英

Python importing from parent's child folder

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

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

My question is how would I import the class.py into the function.py? This setup is very specific and is unable to be changed. What would I need to put in order for this to work?

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 (ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM