-1

I am using Python 3.5 which does not have support for dataclass.

Is there a way to convert the following class to work without 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')}

This is from the locationsharinglib repository

martineau
  • 119,623
  • 25
  • 170
  • 301
Bijan
  • 7,737
  • 18
  • 89
  • 149

1 Answers1

1

You could convert the code to using 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 and not for anything else, writing it out by hand is as simple as:

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')}

Otherwise, the attrs version, avoiding using variable annotations (which are not supported in 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')}

Note, however, that locationsharinglib states in their package metadata that they only support Python 3.7, so you may run into other issues with that project.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Ran `pip install dataclasses` and it installed fine but running `from dataclasses import dataclass` returns Syntax Error for `f'name={self.name!r},'` – Bijan Dec 12 '19 at 21:12
  • Your solution of `self.X = X` worked beautifully. Just had to remove instances of `dataclass` – Bijan Dec 12 '19 at 21:14
  • @Bijan: Ah, sorry, I missed that the project only works on 3.6.. – Martijn Pieters Dec 12 '19 at 21:14