Questions tagged [python-dataclasses]

For questions concerning the Python dataclasses module (new in Python 3.7). Dataclasses are python classes but are specifically suited for storing data objects.

Dataclasses are python classes but are specifically suited for storing data objects(store data and represent a certain data type).

Official documentation: dataclasses

Original proposal: PEP 557

Tutorial / showcase: Raymond Hettinger's talk on PyCon 2018

899 questions
6
votes
1 answer

Why is dataclasses.astuple returning a deepcopy of class attributes?

In the code below the astuple function is carrying out a deep copy of a class attribute of the dataclass. Why is it not producing the same result as the function my_tuple? import copy import dataclasses @dataclasses.dataclass class Demo: …
lemi57ssss
  • 1,287
  • 4
  • 17
  • 36
6
votes
1 answer

Reference class type in dataclass definition

Is it possible to reference the class currently being defined within the class definition? from dataclasses import dataclass from typing import List @dataclass class Branch: tree: List[Branch] Error: NameError: name 'Branch' is not defined
Jack Brookes
  • 3,720
  • 2
  • 11
  • 22
5
votes
2 answers

Make Python dataclass iterable?

I have a dataclass and I want to iterate over in in a loop to spit out each of the values. I'm able to write a very short __iter__() within it easy enough, but is that what I should be doing? I don't see anything in the documentation about an…
scotscotmcc
  • 2,719
  • 1
  • 6
  • 29
5
votes
1 answer

ValueError: mutable default for field headers is not allowed: use default_factory

I am trying to get used with new python's features (dataclasses). I am trying to initialize variables and I get error: raise ValueError(f'mutable default {type(f.default)} for field ' ValueError: mutable default for field headers is…
robotiaga
  • 315
  • 2
  • 11
5
votes
2 answers

How to parse a JSON object into a python dataclass without third party library?

I want to parse json and save it in dataclasses to emulate DTO. Currently, I ahve to manually pass all the json fields to dataclass. I wanted to know is there a way I can do it by just adding the json parsed dict ie. "dejlog" to dataclass and all…
sji gshan
  • 81
  • 1
  • 3
5
votes
2 answers

Annotate dataclass class variable with type value

We have a number of dataclasses representing various results with common ancestor Result. Each result then provides its data using its own subclass of ResultData. But we have trouble to annotate the case properly. We came up with following…
ziima
  • 706
  • 4
  • 17
5
votes
3 answers

How do I convert a json file to a python class?

Consider this json file named h.json I want to convert this into a python dataclass. { "acc1":{ "email":"acc1@example.com", "password":"acc1", "name":"ACC1", "salary":1 }, "acc2":{ …
Kanishk
  • 258
  • 1
  • 3
  • 9
5
votes
1 answer

How to compare dataclasses?

I would like to compare two global dataclasses in terms of equality. I changed the field in one of the dataclasses and python still insists on telling me, that those objects are equal. I don't know how internally dataclasses work, but when I print…
ashrasmun
  • 490
  • 6
  • 11
5
votes
1 answer

how to make class decorated using dataclasses to throw error if different field types are assigned?

I am not sure what I am doing wrong. How to prevent the Test class to accept & throw error, when input of different types are passed. I am using Python 3.9.2 from dataclasses import dataclass, fields @dataclass class Test: a: str = 'a' b:…
Dinesh Ravi
  • 1,209
  • 1
  • 17
  • 35
5
votes
1 answer

Is it possible to freeze a dataclass object in __post_init__() or later?

I'm wondering whether it's possible to "freeze" a dataclass object in post_init() or even after an object was defined. So instead of: @dataclass(frozen=True) class ClassName: var1: type = value Having something like: @dataclass class…
5
votes
1 answer

How to use field() in dataclass?

I often see code like this: @dataclass class ClassName: list_name: list[int] = field(default_factory=list) but I don't understand why I need to type field(default_factory=list). Isn't list_name: list[int] already enough? Could you please…
cwallenwein
  • 538
  • 7
  • 20
5
votes
3 answers

Python: uniqe integer for dataclass?

I have the following data class. @dataclass(frozen=True) class myDataClass: x: float y: float What I want is that every time I create an object of this class, it gets labeled with a unique id which increments from 0. So, the first time I…
adminboss
  • 115
  • 4
5
votes
2 answers

Python: How to get attributes and their type from a dataclass?

I'd like to read all attributes and their types from a (data)class, as shown in this desired (pseudo)code: from dataclasses import dataclass @dataclass class HelloWorld: name: str = 'Earth' is_planet: bool = True radius: int =…
Mr. B.
  • 8,041
  • 14
  • 67
  • 117
5
votes
1 answer

Can the variables defined in the post_init method of dataclasses be serialized?

from dataclasses import dataclass @dataclass class A: x: str y: str def __post_init__(self): self.z = self.x+self.y a = A('abc', 'def') a.z 'abcdef' from dataclasses import asdict asdict(a) {'x': 'abc', 'y': 'def'} As can be…
rivu
  • 2,004
  • 2
  • 29
  • 45
5
votes
2 answers

How to avoid checking for None when setting Optional dataclass args in __post_init__

Consider a dataclass with a mutable default value for an argument. To be able to instantiate an object with a new default value and not a shared mutable object, we can do something like: @dataclass class ClassWithState: name: str items:…
Metropolis
  • 2,018
  • 1
  • 19
  • 36