Any way for python file name to not end up in full

2019-07-21 08:58发布

问题:

Say we have this file structure:

project/
- ticklers/
  - kitten_tickler.py
    - class KittenTickler
  - puppy_tickler.py
    - class PuppyTickler

Assume KittenTickler has enough complexity to not want to share its file with PuppyTickler. The fully qualified names of the defined classes become project.ticklers.kitten_tickler.KittenTickler and project.ticklers.puppy_tickler.PuppyTickler. This is, obviously, redundant. It works well with the usual Python policy of stuffing multiple classes into one file, but it doesn't fit my project. Is there any way to "skip" the file name in the module chain, aggregating puppy_tickler and kitten_tickler contents into ticklers module? Ultimately, I'm interested in having just project.ticklers.PuppyTickler and project.ticklers.KittenTickler.

I tried putting this into project/ticklers/__init__.py:

from .kitten_tickler import KittenTickler
from .puppy_tickler import PuppyTickler

which results in them being accessible in both packages, but KittenTickler.__module__ still ends up being project.ticklers.kitten_tickler (whereas I'd want it as project.ticklers). Additionally, if I do

from project.ticklers import KittenTickler

I will also inadvertently import PuppyTickler as well. So I am not too happy with this approach. Finally, it is not very maintainable.

Am I fighting a losing battle here, or is there a way for me to declare these classes to my satisfaction?