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
15
votes
1 answer

Dataclass: How do I create a field that does not need initializing which is automatically generated?

I used field(init= False) to disable initializing self.ref. It is then a value in post. The following code raises AttributeError: 'Data' object has no attribute 'ref' from dataclasses import dataclass, field def make_list(): return [[0] for k in…
theMobDog
  • 1,251
  • 3
  • 13
  • 26
15
votes
3 answers

Achieving multiple inheritance using python dataclasses

I'm trying to use the new python dataclasses to create some mix-in classes (already as I write this I think it sounds like a rash idea), and I'm having some issues. Behold the example below: from dataclasses import dataclass @dataclass class…
15
votes
6 answers

dataclasses: how to ignore None values using asdict()?

@dataclass class Car: brand: str color: str How can I get a dict that ignore None values? Something like: >>> car = Car(brand="Audi", color=None) >>> asdict(car, some_option_to_ignore_none_values=True) > {'brand': 'Audi'}
David Dahan
  • 10,576
  • 11
  • 64
  • 137
15
votes
3 answers

Pickle a frozen dataclass that has __slots__

How do I pickle an instance of a frozen dataclass with __slots__? For example, the following code raises an exception in Python 3.7.0: import pickle from dataclasses import dataclass @dataclass(frozen=True) class A: __slots__ = ('a',) a: int b…
drhagen
  • 8,331
  • 8
  • 53
  • 82
15
votes
2 answers

Pythonic way to check if a dataclass field has a default value

I've been using python 3.7 lately and was looking for ways to leverage the new dataclasses. Basically I had a method that iterates over the dataclass fields and checks if they have a default value: from dataclasses import fields,…
addonis1990
  • 489
  • 1
  • 6
  • 17
15
votes
0 answers

python (3.7) dataclass for self referenced structure

With the recent introduction to python dataclass decorator, its been quite easy writing model classes. However I am not sure about how to use with the context of self-referencing structure/model class - e.g. LinkedList's internal ListNode/Node model…
Kunal
  • 597
  • 7
  • 19
15
votes
1 answer

Why don't Python 3.7 dataclasses support < > <= and >=, or do they?

For version 3.7.1 of the Transcrypt Python to JavaScript compiler I am currently using the new @dataclass decorator. I had expected that ==, !=, <, >, >=, <= would be supported, as per the PEP's abstract, but it doesn't seem to be the case: from…
Jacques de Hooge
  • 6,750
  • 2
  • 28
  • 45
14
votes
1 answer

Exclude some attributes from __str__ representation of a dataclass

We have this class: from dataclasses import dataclass, field from datetime import datetime from typing import List, Dict @dataclass class BoardStaff: date: str = datetime.now() fullname: str address: str ## attributes to be…
nino
  • 554
  • 2
  • 7
  • 20
14
votes
1 answer

Type-checked conversion between Dataclasses and TypedDicts

I have a bunch of @dataclasses and a bunch of corresponding TypedDicts, and I want to facilitate smooth and type-checked conversion between them. For example, consider from dataclasses import dataclass from typing_extensions import…
Tomas Aschan
  • 58,548
  • 56
  • 243
  • 402
14
votes
3 answers

Json serialization of nested dataclasses

I would need to take the question about json serialization of @dataclass from Make the Python json encoder support Python's new dataclasses a bit further: consider when they are in a nested structure. Consider: import json from attr import…
WestCoastProjects
  • 58,982
  • 91
  • 316
  • 560
14
votes
2 answers

How can I show the code that is generated when using @dataclass class decorator?

Python 3.7 introduces the dataclasses module that contains a @dataclass decorator. This decorator can generate class functions. How can I print these generated functions?
OrangeTux
  • 11,142
  • 7
  • 48
  • 73
14
votes
1 answer

Failed to import dataclasses module

Today I installed python 3.7 from apt-get to try out the new dataclasses module. I installed it seperately because python3.6 wasn't upgradeable to 3.7. When I type: python3.7 --version, it gives me: >>> Python 3.7.0a2 as my current version. The…
user7585980
13
votes
3 answers

Is DataClass a good fit to replace a dictionary?

I use dictionaries as data structure a lot in my code. Instead of returning several value as Tuple like Python permits it : def do_smth(): [...] return val1, val2, val3 I prefer to use a dictionary with the advantage to have named keys. But…
Ragnar
  • 2,550
  • 6
  • 36
  • 70
13
votes
4 answers

How to use spec when mocking data classes in Python

I'm trying to port our namedtuple classes into dataclass in Python 3.6 using the backport package. However, I noticed when mocking dataclass classes, you cannot use the "spec" keyword anymore. I assume it's because the dataclass code is auto…
mohi666
  • 6,842
  • 9
  • 45
  • 51
12
votes
2 answers

Can I have an optional parameter in dataclasses that is omitted when transformed to dict?

I wish to perform static type checking (pylance in vscode) on some dictionaries. The "tricky" part is the I want some of the parameters to be optional and not show up at all in the dictionary. I've tried using dataclasses and TypedDict but without…
mr.bjerre
  • 2,384
  • 2
  • 24
  • 37