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

How to fix 'NameError: name 'field' is not defined'

In my attempt to create a class dots with the fields n and xy as shown below: from dataclasses import dataclass @dataclass class dots: n: int = 200 xy: List[int] = field(default_factory=list) I am constantly getting the error : NameError:…
Kathia
  • 502
  • 2
  • 7
  • 20
10
votes
1 answer

Define an attribute of a dataclass with a reserved word "class" and serialize it

Ok I'm trying to define a dataclass to enqueue a job in redis for a sidekiq worker, the specification of the sidekiq payload requires some attributes something with this format: { "class": "SomeWorker", "queue": "default" "jid":…
10
votes
1 answer

Can I use the Union and Optional types from the typing module when creating a dataclass?

I want to use the Union and Optional types when creating a dataclass. Can I use these types safely? E.g.: @dataclass class Car: year: int owner: Optional[str] engine: Union[Engine1, Engine2]
pynista
  • 241
  • 5
  • 9
10
votes
2 answers

Update a field in a dataclass with a field name known only during runtime

I'd like to update a field within a dataclass, but I know the field name only during runtime, not during development time. #!/usr/bin/env python3.6 # -*- coding: utf-8 -*- from dataclasses import dataclass # I use the backport to…
JDi
  • 131
  • 1
  • 1
  • 5
10
votes
3 answers

Python dataclasses: What type to use if __post_init__ performs type conversion?

I have a Python class, with a field which can be passed one of several sequence types. To simplify I'll stick with tuples and lists. __init__ converts the parameter to MyList. from typing import Union from dataclasses import dataclass, InitVar,…
nyanpasu64
  • 2,805
  • 2
  • 23
  • 31
9
votes
3 answers

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

I would like to ignore the default values after calling asdict() @dataclass class A: a: str b: bool = True so if I call a = A("1") result = asdict(a, ignore_default=True) assert {"a": "1"} == result # the "b": True should be deleted
Nadav
  • 2,589
  • 9
  • 44
  • 63
9
votes
1 answer

TypeError when calling super() in dataclass(slots=True) subclass

I am trying to call a a superclass method from a dataclass with slots=True in Python 3.10.5. from dataclasses import dataclass @dataclass(slots=True) class Base: def hi(self): print("Hi") @dataclass(slots=True) class Sub(Base): …
LeopardShark
  • 3,820
  • 2
  • 19
  • 33
9
votes
1 answer

dataclass inheritance: Fields without default values cannot appear after fields with default values

Context I created two data classes to handle table metadata. TableMetadata apply to any kind of tables, while RestTableMetadata contains information relevant for data extracted from REST apis @dataclass class TableMetadata: """ - entity:…
zar3bski
  • 2,773
  • 7
  • 25
  • 58
9
votes
2 answers

Full copy of an instance of a dataclass with complex structure

I'd like to create a copy of an existing instance of a dataclass and modify it. Suppose we have a dataclass and an instance of that dataclass: from dataclasses import dataclass, field, InitVar, replace @dataclass class D: a: float = 10. …
Roman Zh.
  • 985
  • 2
  • 6
  • 20
9
votes
1 answer

How to compare equality of dataclasses holding numpy.ndarray (bool(a==b) raises ValueError)?

If I create a Python dataclass containing a Numpy ndarray, I can no longer use the automatically generated __eq__ anymore. import numpy as np @dataclass class Instr: foo: np.ndarray bar: np.ndarray arr = np.array([1]) arr2 = np.array([1,…
nyanpasu64
  • 2,805
  • 2
  • 23
  • 31
8
votes
1 answer

TypeError when using super() in a dataclass with slots=True

I have a dataclass with (kind of) a getter method. This code works as expected: from dataclasses import dataclass @dataclass() class A: def get_data(self): # get some values from object's fields # do some calculations …
enkryptor
  • 1,574
  • 1
  • 17
  • 27
8
votes
3 answers

How to iterate over attributes of dataclass in python?

Is it possible to iterate over attributes of a instance of dataclass in python? For example, I would like in the __post_init__ double the integer attributes: from dataclasses import dataclass, fields @dataclass class Foo: a: int b: int …
M.wol
  • 901
  • 3
  • 10
  • 21
8
votes
2 answers

Passing arguments in dataclass representation

I have a below NormalClass that I want to structure as a dataclass. However I was not sure how I can pass the date_str param without __init__ in the dataclass. Any thoughts? class FieldDateTime(): def __init__(self, data, d_format='%m/%d/%y…
Venu Family
  • 83
  • 1
  • 4
8
votes
1 answer

What explains the different performance of creating objects via normal class, dataclass and namedtuple?

I was going through data classes and named tuple. I found this behaviour where creating objects using different features of python have different performance. dataclass: In [1]: from dataclasses import dataclass ...: ...: @dataclass ...:…
8
votes
5 answers

Weird Issue when using dataclass and property together

I ran into a strange issue while trying to use a dataclass together with a property. I have it down to a minumum to reproduce it: import dataclasses @dataclasses.dataclass class FileObject: _uploaded_by: str = dataclasses.field(default=None,…
Michael Robellard
  • 2,268
  • 15
  • 25