Reputation: 31
I'm trying to create a python dataclass that contains some data alongside position data in the type of tuple (x, y) as shown in the following code:
@dataclass_json
@dataclass
class ObjectData:
# ...
position: tuple = (0, 0)
I need to obtain data in JSON format, so this is what I should do to fill my ObjectData attributes directly from JSON.
data = get_json_data() # a function that returns a string of JSON formatted data
my_object = ObjectData().from_json(data)
However I always obtain this error:
AttributeError: type object 'tuple' has no attribute '__args__'. Did you mean: '__add__'?
I tried to convert JSON to python dict:
from ast import literal_eval # to parse tuple from string
import json
data = get_json_data()
data = json.loads(data)
data['position'] = literal_eval(data['position'])
my_object = ObjectData().from_dict(data)
Gives the same output:
AttributeError: type object 'tuple' has no attribute '__args__'. Did you mean: '__add__'?
Here's a full snippet of the error
File "$WORKING_PATH/lib/python3.10/site-packages/dataclasses_json/api.py", line 72, in from_dict
return _decode_dataclass(cls, kvs, infer_missing)
File "$WORKING_PATH/lib/python3.10/site-packages/dataclasses_json/core.py", line 201, in _decode_dataclass
init_kwargs[field.name] = _decode_generic(field_type,
File "$WORKING_PATH/lib/python3.10/site-packages/dataclasses_json/core.py", line 258, in _decode_generic
xs = _decode_items(type_.__args__[0], value, infer_missing)
AttributeError: type object 'tuple' has no attribute '__args__'. Did you mean: '__add__'?
EDIT: position tuple can contain a string too, for example ('top', 55)
Upvotes: 1
Views: 1217
Reputation: 31
I fixed the issue by adding type hinting
@dataclass_json
@dataclass
class ObjectData:
# ...
position: tuple[int, int] = (0, 0)
and because I needed the tuple to contain string or integer types as coordinates
from typing import Any
@dataclass_json
@dataclass
class ObjectData:
# ...
position: tuple[Any, Any] = (0, 0)
Now I can obtain data from json to python dataclass. If there's a better method please let me know. Hope that helps someone.
Upvotes: 1