我在一個項目中做了一個相當有意思的導入方案,我想我可能在Python解釋器中發現了一個導致模塊導入兩次的錯誤。模塊導入兩次。 Python解釋器中可能存在的錯誤
這裏是我的測試項目是如何設置的:
/
Launcher.bat —項目就是從這裏跑。它啓動「使用Python 3.2可執行
主/ __ init__.py —的
__main__
腳本主/ __ __初始化。py`,一個是推出 'Launcher.bat'主/ foo中。 PY —包含一個空類
外部/ __ init__.py —腳本外部的「主」工程腳本,用來說明問題
./Launcher.bat
@echo off
C:\Python32\python.exe main\__init__.py
pause
./main/__init__.py
from foo import Foo
print("In 'main', Foo has id:", id(Foo))
# Add the directory from which 'Launcher.bat' was run,
# which is not the same as the './main' directory
# in which this script is located
import sys
sys.path.insert(1, '.')
# This script will try to import class Foo, but in doing so
# will casue the interpreter to import this './main/__init__.py'
# script a second time.
__import__('external')
./main/foo.py
class Foo:
pass
./external/__init__.py
from main.foo import Foo
print("In 'external', Foo has id:", id(Foo))
所有這一切都將打印'Main script was imported'
消息的兩倍。如果外部腳本導入任何其他腳本,那麼這些腳本也將被導入兩次。我只在Python 3.2上測試過。這是一個錯誤,還是我犯了一個錯誤?該方案的
輸出是:
在 '主',富具有ID:12955136
在 '主',富具有ID:12955136
在 '外部',富具有ID:12957456
按任意鍵繼續。 。 。
它總是讓我笑聲明:我的代碼工作,python有一個bug:D – fabrizioM 2011-12-27 18:21:26
@fabrizioM然後,你不能真正說你會期望Python導入相同的模塊兩次。我現在知道它爲什麼會發生,但我仍然認爲它不應該發生。 – 2011-12-27 18:24:23