Tôi đã theo hệ thống phân cấp dự án:Nhập lớp thư viện trong Python
project_dir
lib
__init__.py
...
some_script.py
...
agent
__init__.py
...
errors.py
some_agent_script.py
...
Có định nghĩa lớp SomeException trong lib/đại lý/erros.py tôi sử dụng đoạn mã sau để nhập khẩu bên trong lib/đại lý/some_agent_script. py:
from errors import SomeException
Ngoài ra tôi sử dụng đoạn mã sau để nhập khẩu trong lib/some_script.py
from agent.errors import SomeException
.210
Vấn đề là khi tôi nâng cao một SomeException trong lib/đại lý/some_agent_script.py sau đó lib/some_script.py không thể bắt nó trong một ngoại trừ khối:
try:
# Here comes a call to lib/agent/some_agent_script.py function
# that raises SomeException
except SomeException, exc:
# Never goes here
print(exc)
except Exception, exc:
print(exc.__class__.__name__) # prints "SomeException"
# Let's print id's
print(id(exc.__class__))
print(id(SomeException))
# They are different!
# Let's print modules list
pprint.pprint(sys.modules)
tôi có thể nhìn thấy trong sys.modules rằng erros mô-đun được nhập khẩu hai lần: đầu tiên là với 'agent.errors' chìa khóa và thứ hai là với chính
các mã sau 'lib.agent.errors' đi đúng, nhưng nó không phải là một giải pháp tuyệt đẹp:
agent_errors = sys.modules.get('agent.errors')
from agent_errors import SomeException
try:
# Here comes a call to lib/agent/some_agent_script.py function
except SomeException:
print('OK')
Tôi nên làm gì để làm cho mô-đun này không được nhập hai lần?
Phiên bản Python là gì? –
Đó là Python 2.6.6 – fey
Đọc liên quan: [SO câu hỏi] (http://stackoverflow.com/questions/1459236/module-reimported-if-imported-from-different-path), [PEP 395] (http://www.python.org/dev/peps/pep-0395/) –