给定以下软件包:
testpackage
__init__.py
testmod.py
testmod2.py
的内容__init__.py
from . import testmod
from . import testmod2
的内容testmod.py
# relative import without conditional logic, breaks when run directly
from . import testmod2
...
if __name__ == '__main__':
# do my module testing here
# this code will never execute since the relative import
# always throws an error when run directly
的内容testmod2.py
if __name__ == 'testpackage.testmod2':
from . import testmod
else:
import testmod
...
if __name__ == '__main__':
# test code here, will execute when the file is run directly
# due to conditional imports
这很糟糕吗?有没有更好的办法?