How to import custom python package by name

前端 未结 2 2154
醉酒成梦
醉酒成梦 2021-01-07 05:09

I have created a folder named \"custom_module\" and I have the __init__.py inside the folder which contains:

__all__ = [
        \'Submodule1\',
        \'Su         


        
相关标签:
2条回答
  • 2021-01-07 05:25

    There are two distinct concepts you are confusing: packages and modules.

    A module is what you think it is: a Python script containing classes, variables, whatever. You import it by its filename, and can then access the variables in its namespace.

    A package is a collection of modules which are grouped together inside a folder. If the folder contains a file called __init__.py, Python will allow you to import the entire folder as if it were a module. This will run the code in __init__, but will not necessarily import all of the modules in the folder. (This is a deliberate design choice: packages are often very large, and importing all of the modules could take a very long time.)

    The only things which are exported (as package.thing) by default are the variables defined inside __init__. If you want submodule to be available as package.submodule, you need to import it inside __init__.

    __all__ is a related concept. In brief, it defines what is imported when you do from package import *, because it's not easy for Python to work out what that should be otherwise. You don't in general need it.

    0 讨论(0)
  • 2021-01-07 05:27

    sys.path holds the Python search path. Before trying to import your modules and packages, set it to include your path:

    import sys
    sys.path.insert(0, 'your_path_here')
    import custom_module
    

    More detail in the Python docs and in this question

    0 讨论(0)
提交回复
热议问题