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.
Similar Posts:
- Python Attempted relative import in non-package,ImportError: cannot import name ‘xx’ from ‘__main
- [Solved] ImportError:attempted relative import with no known parent package
- [Solved] rosrun import rospy Error: ImportError: No module named yaml
- [Solved] “import numpy as np” ImportError: No module named numpy
- [Solved] ModuleNotFoundError: No module named’usysconfigdata u x86 64-u-gnu’
- Ubuntu18.04 (Python3.9) Error: ImportError: Cannot import name ‘sysconfig’ from ‘distutils’
- [Solved] peewee error: ImportError: No module named ‘MySQLdb’;pymysql error: from . import connections # noqa: E402
- [Solved] ImportError: cannot import name ‘cached_property’ from ‘werkzeug’
- docker:ImportError: libcuda.so.1: cannot open shared object file: No such file or directory
- Error in PIP3 execution of multi version Python by windows: module ‘enum’ has no attribute ‘intflag’?