1

I'm looking for a pythonic way to deal with the following package structure problem.

In my project I implemented a couple of file parsers. This was my first idea of the packaging structure:

myproject
└── parsers
    ├── __init__.py
    ├── parser_a.py
    └── parser_b.py

The drawback of this approach is that the required imports are rather verbose:

from myproject.parser.parser_a import Parser_A
from myproject.parser.parser_b import Parser_B

I think this import would be nicer:

from myproject.parser import Parser_A
from myproject.parser import Parser_B

There are at least two ways to achieve this:

i) Putting all parsers in one huge python module.

myproject
└── parser.py

But this would result in a huge, probably confusing parser.py file

ii) Splitting the parser.py module over multiple files[1]

myproject
├── parser.py
└── parsers
    ├── __init__.py
    ├── parser_a.py
    └── parser_b.py

Content of parser.py:

from parsers.parser_a import ParserA
from parsers.parser_b import ParserB

This approach avoids the one-file problem, but imo it looks a little hacky.

It's probably a matter of opinion but I'm looking for a pythonic way to deal with that kind of problem. Is it acceptable to use those shortened, java-like imports? And if so - what is the preferred way?

1 Answer 1

5

Personally I would put everything in parser.py

Another common option is to have this layout:

myproject
└── parsers
    ├── __init__.py
    ├── parser_a.py
    └── parser_b.py

and have the following content in __init__.py:

from parsers.parser_a import ParserA
from parsers.parser_b import ParserB

There isn't really one specific rule for this, so it is up to you what to use.

Remember that python isn't java. It is totally fine to define multiple classes in one file.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.