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
12
votes
2 answers

Dataclass not inheriting __eq__() method from its parent

I have a parent dataclass and a sub-dataclass inherits the first class. I've redefined __eq__() method in parent dataclass. But when I compare objects sub-dataclass, it doesn't use the __eq__() method defined in parent dataclass. Why is this…
Nagabhushan S N
  • 6,407
  • 8
  • 44
  • 87
12
votes
1 answer

How to enforce dataclass fields' types?

In this code: import dataclasses @dataclasses.dataclass class MyClass: value: str obj = MyClass(value=1) the dataclass MyClass is instantiated with a value that does not obey the value type. Is there a simple way (using a decorator, an…
Jundiaius
  • 6,214
  • 3
  • 30
  • 43
12
votes
1 answer

How to declare an array or a list in a Python @dataclass?

How can I declare an array (or at least list) in @dataclass? A something like below: from dataclasses import dataclass @dataclass class Test(): my_array: Array[ChildType]
11
votes
1 answer

How to reference `self` in dataclass' fields?

I am trying to do the equivalent of: class A: def __init__(self): self.b = self.get_b() def get_b(self): return 1 using @dataclass. I want to use a @dataclass here because there are other (omitted) fields initialized from…
Mario Ishac
  • 5,060
  • 3
  • 21
  • 52
11
votes
2 answers

Unable to Instantiate Python Dataclass (Frozen) inside a Pytest function that uses Fixtures

I'm following along with Architecture Patterns in Python by Harry Percival and Bob Gregory. Around chapter three (3) they introduce testing the ORM of SQLAlchemy. A new test that requires a session fixture, it is throwing AttributeError,…
matabeitt
  • 160
  • 9
11
votes
2 answers

Abstract dataclass without abstract methods in Python: prohibit instantiation

Even if a class is inherited from ABC, it can still be instantiated unless it contains abstract methods. Having the code below, what is the best way to prevent an Identifier object from being created: Identifier(['get', 'Name'])? from abc import…
Hlib Babii
  • 599
  • 1
  • 7
  • 24
11
votes
1 answer

Dict from nested dataclasses

I'm wondering how could I transform nested dataclasses to dict except for None fields. I'm aware of asdict() method existence, but I'm trying to write method similar to asdict() that will ignore empty values during dict creation. For…
slqq
  • 245
  • 2
  • 3
  • 13
11
votes
1 answer

How can I use a list[customClass] as type with @dataclass in Python 3.7.x

I have the following dataclasses. @dataclass class Package: '''Class for keeping track of one destination.''' _address: [] @dataclass class Destination: '''Class for keeping track of a destination.''' _start: str _end: str _distance:…
RandomNumberFun
  • 638
  • 2
  • 8
  • 25
10
votes
2 answers

How to define `__str__` for `dataclass` that omits default values?

Given a dataclass instance, I would like print() or str() to only list the non-default field values. This is useful when the dataclass has many fields and only a few are changed. @dataclasses.dataclass class X: a: int = 1 b: bool = False c:…
Hugues
  • 2,865
  • 1
  • 27
  • 39
10
votes
2 answers

How to override names of dataclasses attributes in Python?

I am using dataclass to parse (HTTP request/response) JSON objects and today I came across a problem that requires transformation/alias attribute names within my classes. from dataclasses import dataclass, asdict from typing import List import…
Milovan Tomašević
  • 6,823
  • 1
  • 50
  • 42
10
votes
1 answer

what is field metadata used for in python dataclasses

I have been reading through documentation for python dataclasses and other web pages. The field metadata is read-only and the documentation says: It is not used at all by Data Classes and is provided as a third-party extension mechanism I'm…
armen
  • 403
  • 5
  • 16
10
votes
1 answer

How to overwrite Python Dataclass 'asdict' method

I have a dataclass, which looks like this: @dataclass class myClass: id: str mode: str value: float This results in: dataclasses.asdict(myClass) {"id": id, "mode": mode, "value": value} But what I want is {id:{"mode": mode, "value":…
Markus
  • 125
  • 1
  • 6
10
votes
3 answers

Update dataclass fields from a dict in python

How can I update the fields of a dataclass using a dict? Example: @dataclass class Sample: field1: str field2: str field3: str field4: str sample = Sample('field1_value1', 'field2_value1', 'field3_value1',…
Nagabhushan S N
  • 6,407
  • 8
  • 44
  • 87
10
votes
3 answers

Typing: Restrict to a list of strings

This is Python 3.7 I have a dataclass like this: @dataclass class Action: action: str But action is actually restricted to the values "bla" and "foo". Is there a sensible way to express this?
Christian Sauer
  • 10,351
  • 10
  • 53
  • 85
10
votes
2 answers

How to remove dataclass attributes

I have a dataclass like this: @dataclass class Bla: arg1: Optional[int] = None arg2: Optional[str] = None arg3: Optional[Dict[str, str]] = None I want this behavior: >>> bla = Bla(arg1=None, arg2=None, arg3=None) >>>…
GustavoIP
  • 873
  • 2
  • 8
  • 25