What is __path__ useful for?

后端 未结 4 1897
长情又很酷
长情又很酷 2020-11-28 03:57

I had never noticed the __path__ attribute that gets defined on some of my packages before today. According to the documentation:

Packag

4条回答
  •  清酒与你
    2020-11-28 04:45

    A particular situation I've come across is when a package becomes large enough that I want to split parts of it into subdirectories without having to change any code that references it.

    For example, I have a package called views that was collecting a number of supporting utility functions that were getting muddled with the main top-level purpose of the package. I was able to move these supporting functions into a subdirectory utils and add the following line to the __init__.py for the views package:

    __path__.append(os.path.join(os.path.dirname(__file__), "utils"))
    

    With this change too views/__init_.py, I could run the rest of the software with the new file structure without any further changes to the files.

    (I tried to do something similar with import statements in the views/__init__.py file, but the sub-package modules were still not visible through an import of the view package - I'm not entirely sure if I'm missing something there; comments on that welcome!)

    (This response based on Python 2.7 installation)

提交回复
热议问题