2 に答える
I can illustrate what is causing the difference between each import, but I'm not expert enough on Python's import process to be able to explain the why very well.
>>> import sys
>>> before_import = set(sys.modules.keys())
>>> import mypkg
imported module_a
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "mypkg\__init__.py", line 2, in <module>
yarg ## cause import error
NameError: name 'yarg' is not defined
>>> after_import = set(sys.modules.keys())
>>> after_import.difference(before_import)
set(['mypkg.module_a'])
When you import mypkg, it successfully imports module_a and adds it to sys.modules. Then mypkg errors and doesn't get added itself to the sys.modules dictionary. Deleting the entry allows you to reimport with the same error:
>>> import sys
>>> del sys.modules['mypkg.module_a']
>>> import mypkg
imported module_a
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "mypkg\__init__.py", line 2, in <module>
yarg ## cause import error
NameError: name 'yarg' is not defined
Now, what I think is happening is:
import mypkgstarts the import process formypkgAs it's processing
mypkg, it successfully importsmodule_aas a subpackage of itself and adds it tosys.modulesWhen it hits the error, the import process for
mypkgfails and no entry formypkgis left insys.modulesThe conjunction of the package failing but the subpackage succeeding conflicts with subsequent imports
That's about the best I can fathom, sorry. Python's import process is something of a black art.
問題は、パッケージの読み込みに失敗していることだと確信しています。ファイルに(yargそれ自体で)意味のないものを入れました。__init__.pyこれは、mypkgインポートできないことを意味します。このため、mypkg.module_aインポートもできません。
Pythonがモジュール状態のキャッシュを行っているため、別のエラーが発生する可能性があります。初めてインポートを試みるときは、ロード中であってもmypkg、そのサブモジュールのインポートが許可されます。2回目は、正しく機能しないという事実がキャッシュされるため、親パッケージが壊れているため、ロードに失敗します。module_amypkgmypkgmypkg.module_a