删除数据类依赖

Remove dataclass dependency

我正在使用 Python 3.5,它不支持 dataclass

有没有办法将以下 class 转换为在没有 dataclasses 的情况下工作?

from dataclasses import dataclass

@dataclass
class Cookie:
    """Models a cookie."""

    domain: str
    flag: bool
    path: str
    secure: bool
    expiry: int
    name: str
    value: str

    def to_dict(self):
        """Returns the cookie as a dictionary.

        Returns:
            cookie (dict): The dictionary with the required values of the cookie

        """
        return {key: getattr(self, key) for key in ('domain', 'name', 'value', 'path')}

这来自 locationsharinglib 存储库

您可以将代码转换为使用 attrs (which inspired dataclasses) or just write out the class by hand. Given that the project you link to uses the class purely as a temporary dataholder 而不是其他任何东西,手写它就像:

class Cookie:
    """Models a cookie."""
    def __init__(self, domain, flag, path, secure, expiry, name, value):
        self.domain = domain
        self.flag = flag
        self.path = path
        self.secure = secure
        self.expiry = expiry
        self.name = name
        self.value = value

    def to_dict(self):
        """Returns the cookie as a dictionary.
        Returns:
            cookie (dict): The dictionary with the required values of the cookie
        """
        return {key: getattr(self, key) for key in ('domain', 'name', 'value', 'path')}

否则,attrs版本,避免使用变量注解(3.5不支持):

@attr.s
class Cookie:
    """Models a cookie."""

    domain = attr.ib()
    flag = attr.ib()
    path = attr.ib()
    secure = attr.ib()
    expiry = attr.ib()
    name = attr.ib()
    value = attr.ib()

    def to_dict(self):
        """Returns the cookie as a dictionary.
        Returns:
            cookie (dict): The dictionary with the required values of the cookie
        """
        return {key: getattr(self, key) for key in ('domain', 'name', 'value', 'path')}

但是请注意,locationsharinglib states in their package metadata 它们仅支持 Python 3.7,因此您可能 运行 遇到该项目的其他问题。