Reserved word as an attribute name in a dataclass when parsing a JSON object

Question:

I stumbled upon a problem, when I was working on my ETL pipeline. I am using dataclasses dataclass to parse JSON objects. One of the keywords of the JSON object is a reserved keyword. Is there a way around this:

from dataclasses import dataclass
import jsons

out = {"yield": 0.21}

@dataclass
class PriceObj:
    asOfDate: str
    price: float
    yield: float

jsons.load(out, PriceObj)

This will obviously fail because yield is reserved. Looking at the dataclasses field definition, there doesn’t seem to be anything in there that can help.

Go, allows one to define the name of the JSON field, wonder if there is such a feature in the dataclass?

Asked By: Naz

||

Answers:

You can decode / encode using a different name with the dataclasses_json lib, from their docs:

from dataclasses import dataclass, field

from dataclasses_json import config, dataclass_json

@dataclass_json
@dataclass
class Person:
    given_name: str = field(metadata=config(field_name="overriddenGivenName"))

Person(given_name="Alice")  # Person('Alice')
Person.from_json('{"overriddenGivenName": "Alice"}')  # Person('Alice')
Person('Alice').to_json()  # {"overriddenGivenName": "Alice"}
Answered By: Naz

I found next solution for my purposes.

@dataclass
class ExampleClass:
    def __post_init__(self):
        self.__setattr__("class", self.class_)
        self.__delattr__("class_") 

    class_: str

It requires to set init value in ‘class_’ attribute.

Answered By: Pavlo Doroshenko