What is __path__ useful for?

后端 未结 4 1976
长情又很酷
长情又很酷 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:59

    In addition to selecting different versions of a module based on runtime conditions as Syntactic says, this functionality also would allow you to break up your package into multiple pieces / downloads / installs while maintaining the appearance of a single logical package.

    Consider the following.

    • I have two packages, mypkg and _mypkg_foo.
    • _mypkg_foo contains optional module to mypkg, foo.py.
    • as downloaded and installed, mypkg doesn't contain a foo.py.

    mypkg's __init__.py can do something like so:

    try:
        import _mypkg_foo
        __path__.append(os.path.abspath(os.path.dirname(_mypkg_foo.__file__)))
        import mypkg.foo
    except ImportError:
        pass
    

    If someone has installed the package _mypkg_foo, then mypkg.foo is available to them. If they haven't, it doesn't exist.

提交回复
热议问题