简体   繁体   中英

Python Package Folder Structure

I have been researching how to build the folder structure for a custom python package. There were several attempts, but none of them seemed to be applicable in general. In particular, the usage (or not usage) of the \\__init__.py file(s).

I have a package that consists of several sub-packages, each being responsible to parse Files of a certain kind. Therefore I currently adopted this structure:

Parsers/
├── __init__.py
|
├── ExternalPackages
│   ├── __init__.py
│   ├── package1
│   └── package2
|
├── FileType1_Parsers/
│   ├── __init__.py
│   ├── parsers1.py
│   └── containers1.py
│   
└── FileType2_Parsers/
    ├── __init__.py
    ├── parsers2.py
    └── containers2.py

But it seems not very pythonic, that when I import his package and I want to use a certain class of a module I have to type something like

from Parsers.FileType1_Parsers.parsers1 import example_class

Is there any convention on how to structure such packages or any rules on how to avoid such long import lines?

You can add the following line to Parsers/__init__.py

from .FileType1_Parsers.parsers1 import example_class

Then you can import example_class by

from Parsers import example_class

This is a common practice in large package.

You can modify sys.path at run-time so that it contains a directory for each module you'll be using. For example, for package1 issue the following statements:

>>> sys.path.append(r"[package directory path]\\Parsers\\FileType1_Parsers\\package1")

You can do this for any other modules in the package as well. Now, you can just use this command:

from package1 import example_class

Hope this helps!

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