我“借用”了以下單例裝飾器:
class Singleton:
def __init__(self, decorated: Callable) -> None:
self._decorated = decorated
self.initialized = False
def Instance(self) -> Callable:
"""
Returns the singleton instance. Upon its first call, it creates a
new instance of the decorated class and calls its `__init__` method.
On all subsequent calls, the already created instance is returned.
"""
try:
return self._instance
except AttributeError:
self._instance = self._decorated()
return self._instance
def Initialize(self, *args, **kwargs) -> Callable:
if self.initialized:
raise Exception("Singleton already initialized")
self._instance = self._decorated(*args, **kwargs)
self.initialized = True
return self._instance
def __call__(self) -> Callable:
if not self.initialized:
raise Exception("Singleton not initialized")
return self._instance
def __instancecheck__(self, inst):
return isinstance(inst, self._decorated)
我在這里應用了它:
@Singleton
class x_DB(DBHandler):
def __init__(self, db_loc:Path):
self.check_db_exists(db_loc)
super().__init__(db_loc)
self.query = self.session.query
self.check_tables_exist()
self.check_for_global()
def check_db_exists(self, path:Path) -> bool:
if not path.exists():
logger.debug(f"DB: {path} does not exist, creating..")
path.touch()
logger.success(f"Successfully created {path}")
return True
...
現在,通常當我使用 db 類的實體時,我會得到如下提示:

但由于某種原因,我的提示都是這樣的:

有什么技巧可以解決這個問題并讓我的型別提示回來嗎?
嘗試過弄亂打字包,更新pylance,回傳絕地,安裝pyright等。但似乎沒有任何效果
uj5u.com熱心網友回復:
自動完成高度依賴于 IDE 的內置型別檢查器,而裝飾器因混淆型別檢查器而臭名昭著。一種解決方案是使您的單例顯式鍵入:
from collections.abc import Callable
from pathlib import Path
from typing import TypeVar, Generic, Type
T = TypeVar('T')
class Singleton(Generic[T]):
def __init__(self, decorated: Type[T]) -> None:
self._decorated = decorated
self.initialized = False
def Instance(self) -> T:
"""
Returns the singleton instance. Upon its first call, it creates a
new instance of the decorated class and calls its `__init__` method.
On all subsequent calls, the already created instance is returned.
"""
try:
return self._instance
except AttributeError:
self._instance = self._decorated()
return self._instance
def Initialize(self, *args, **kwargs):
if self.initialized:
raise Exception("Singleton already initialized")
self._instance = self._decorated(*args, **kwargs)
self.initialized = True
return self._instance
def __call__(self) -> T:
if not self.initialized:
raise Exception("Singleton not initialized")
return self._instance
def __instancecheck__(self, inst):
return isinstance(inst, self._decorated)
這在 PyCharm 和 VS Code 中對我有用。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/522106.html
