Any way for python file name to not end up in fully qualified name?

一个人想着一个人 提交于 2019-12-11 02:26:07

问题


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?

来源:https://stackoverflow.com/questions/51722449/any-way-for-python-file-name-to-not-end-up-in-fully-qualified-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!