是否可以将抽象基类用作 dict 子类的混合?

问题描述

TL;DR:想知道是否可以按照我想要的方式使用抽象基类作为混合,或者我的方法是否从根本上被误导了。

我有一个正在处理的 Flask 项目。作为我项目的一部分,我实现了一个 RememberingDict 类。它是 dict一个简单子类,附加了一些额外的功能:它记住它的创建时间,它知道如何将自己腌制/保存到磁盘,以及它知道如何从磁盘中打开/解开自己:

from __future__ import annotations

import pickle
from datetime import datetime
from typing import Final,Optional,TypeVar,Any,Hashable


FILE_PATH: Final = 'data.pickle'
T = TypeVar('T',bound='RememberingDict')


class RememberingDict(dict):
    def __init__(self,data: Optional[dict[Hashable,Any]] = None) -> None:
        super().__init__(data if data is not None else {})
        self.creation_time: datetime = datetime.Now()

    def to_disk(self) -> None:
        """I save a copy of the data to a file"""

        with open(FILE_PATH,'wb') as f:
            pickle.dump(self,f)

    @classmethod
    def from_disk(cls: type[T]) -> T:
        """I extract a copy of the data from a file"""

        with open(FILE_PATH,'rb') as f:
            latest_dataset: T = pickle.load(f)

        return latest_dataset

代码在本地开发服务器上非常适合我的目的,所以一切都很好,但是(由于没有必要在这里介绍的原因),它在 Google App Engine 上部署时不起作用,所以为了这些目的,我设计了这个替代实现:

from __future__ import annotations

import pickle
from datetime import datetime
from typing import Optional,TypeVar
from google.cloud.storage.blob import Blob


def get_google_blob() -> Blob:
"""
Actual implementation unnecessary to go into,but rest assured that the real version of this function returns a Blob object,linked to Google Storage account credentials,from which files can be uploaded to,and downloaded from,Google's Cloud Storage platform.
"""
    pass


T = TypeVar('T',Any]] = None) -> None:
        super().__init__(data if data is not None else {})
        self.creation_time: datetime = datetime.Now()

    def to_disk(self) -> None:
        """I upload a copy of the data to Google's Cloud Storage"""

        get_google_blob().upload_from_string(pickle.dumps(self))

    @classmethod
    def from_disk(cls: type[T]) -> T:
        """I extract a copy of the data from Google's Cloud Storage"""

        latest dataset: T = pickle.loads(get_google_blob().download_as_bytes())
        return latest_dataset

现在,这两种实现都可以正常工作。然而,我想同时保留它们——第一个对开发有用——但令人讨厌的是,两者之间显然有相当多的重复。它们的 __init__() 函数是相同的;它们都有一个 to_disk() 方法,可以将实例保存到文件中并返回 None;并且它们都有一个 from_disk()方法,该方法返回已保存到磁盘某处的类的实例。

理想情况下,我希望它们都继承自一个基类,该基类向它们传递了各种类似 dict 的能力,并且还指定了 to_disk()from_disk() 方法必须被覆盖才能提供完整的实现。

这感觉是一个 ABC 应该能够解决的问题。我尝试了以下方法

from __future__ import annotations

from datetime import datetime
from typing import Final,Hashable
from abc import ABC,abstractmethod
from google.cloud.storage.blob import Blob


T = TypeVar('T',bound='AbstractRememberingDict')


class AbstractRememberingDict(ABC,dict):
    def __init__(self,Any]] = None) -> None:
        super().__init__(data if data is not None else {})
        self.creation_time: datetime = datetime.Now()
    
    @abstractmethod
    def to_disk(self) -> None: ...

    @classmethod
    @abstractmethod
    def from_disk(cls: type[T]) -> T: ...


FILE_PATH: Final = 'data.pickle'


class LocalRememberingDict(AbstractRememberingDict):
    def to_disk(self) -> None:
        """I save a copy of the data to a file"""

        with open(FILE_PATH,'rb') as f:
            latest_dataset: T = pickle.load(f)

        return latest_dataset


def get_google_blob() -> Blob:
"""
Actual implementation unnecessary to go into,Google's Cloud Storage platform.
"""
    pass


class RemoteRememberingDict(AbstractRememberingDict):
    def to_disk(self) -> None:
        """I upload a copy of the data to Google's Cloud Storage"""

        get_google_blob().upload_from_string(pickle.dumps(self))

    @classmethod
    def from_disk(cls: type[T]) -> T:
        """I extract a copy of the data from Google's Cloud Storage"""

         latest_dataset: T = pickle.loads(get_google_blob().download_as_bytes())
         return latest_dataset 

然而,使用 ABC 作为混合(而不是作为唯一的基类)似乎与 @abstractmethod 装饰器混淆,这样继承的类如果无法实现就不再引发异常所需的抽象方法

理想情况下,我希望我的基类继承标准 Python dict 的所有功能,但还指定必须在继承的类中实现某些方法才能实例化实例。

我正在尝试做的事情是可能的,还是我的方法从根本上被误导了?

(顺便说一句:我对 ABC 的工作方式更感兴趣,而不是为 Web 应用程序缓存数据结构的最佳方法等。我相信可能有更好的方法缓存数据,但这是我的第一个 Flask 项目,目前我的方式非常适合我。)

解决方法

您可以通过子类化 collections.UserDict 来解决子类化 dict 的问题。正如文档所说:

模拟字典的类。实例的内容保存在常规字典中,可通过 UserDict 实例的 data 属性访问。如果提供了initialdata,则用其内容初始化数据;请注意,将不会保留对 initialdata 的引用,以便将其用于其他目的。

本质上,它是一个围绕 dict 的薄常规类包装器。您应该能够将它与多重继承一起用作抽象基类,就像使用 AbstractRememberingDict 一样。