Defect: __mian__ cannot use relative import
PEP 328 Relative Imports and __name__ states:
Relative imports use a module’s __name__ attribute to determine that module’s position in the package hierarchy. If the module’s name does not contain any package information (e.g. it is set to ‘__main__’) then relative imports are resolved as if the module were a top level module, regardless of where the module is actually located on the file system.
That is: relative import in the package hierarchy, use the __name__ attribute of the module to get the location of the module. But if the name of the module does not contain any package information (for example, __main__ module), regardless of whether the module is actually located in the file system, relative imports will be imported as a top level module.
According to the recommendations of 6.4.2. Intra-package References :
Note that relative imports are based on the name of the current module. Since the name of the main module is always “__main__”, modules intended for use as the main module of a Python application must always use absolute imports.
__mian__ use Absolute import
manner, while still using other modulesRelative Import
if __name__ == '__main__':
sys.path.append(os.path.dirname(sys.path[0]))
Import method
Refer to stackoverflow vaultah’s answer, which is more detailed, so I won’t repeat it here.
Why choose the advantage of relative import
PEP 328 Rationale for Relative Imports states:
Several use cases were presented, the most important of which is being able to rearrange the structure of large packages without having to edit sub-packages.In addition, a module inside a package can’t easily import itself without relative imports.
That is: relative import can rebuild large python packages without re-editing sub-packages; in addition, relative import can import itself relatively easily.