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.

Filter by
Sorted by
Tagged with
1 vote
1 answer
61 views

Why does assigning a default to a dataclass field, make it into a class attribute?

When you add a field to a python dataclass, it will become a required argument for __init__ and it will be an instance attribute. But when you add a default value to a field it becomes a class ...
mahkitah's user avatar
  • 626
0 votes
1 answer
54 views

Using class methods to return instances and simply defining __init__(self, **kwargs):

One pattern I recently started using is writing class methods to return instances. In particular, I've been using it for dataclasses (with or without the @dataclass decorator). But it has also led me ...
shridhar singh's user avatar
0 votes
2 answers
75 views

Convert dataclass containing set of another dataclass to nested dictionary

I have the following dataclasses: # model.py from dataclasses import dataclass from typing import Optional @dataclass(frozen=True) class Location: x: int y: int def __lt__(self, other): ...
JGG's user avatar
  • 41
2 votes
1 answer
42 views

Monitor function calls inside python contexts

Using python I would like to: monitor execution of some 'selected' functions (I would like to record function name, execution time, etc.) store these info only when functions are executed inside a ...
hari's user avatar
  • 164
2 votes
1 answer
50 views

Python dataclass automate ID incrementation in abstract class

I want to create a unique ID incrementation for my Python subclasses using the abstract method, but I don't know how to separate each subclass's set of ID values. Here is my code: from dataclasses ...
Alex's user avatar
  • 1,273
0 votes
1 answer
71 views

How to mutate dataclass argument upon instantiation?

I have a dataclass that looks like this: @dataclass class AllLastTick: tick_type_mapping = { 0: "bid_size", 1: "bid_price", 2: "ask_price", ...
Jason Strimpel's user avatar
2 votes
2 answers
79 views

Why does dataclass favour __repr__ over __str__?

Given the following code, I think output (A) makes sense since __str__ takes precedence over __repr__ however I am a bit confused about output (B) why does it favour __repr__ over __str__ and is there ...
Tobias Wilfert's user avatar
1 vote
1 answer
39 views

dictionary get method for list of dataclass objects - find dataclass with specific variable value in list of dataclasses

###It seems to me there has to be nicer way find a dataclass object than to loop through all to find the specific one. #My way, that I hope to improve: def changeValueOf(primaryKey): for item in ...
Schradt's user avatar
  • 13
0 votes
0 answers
20 views

Python dataclass initialization and updating its field [duplicate]

I just started learning Python and have a question about dataclass initialization and updating its field using a function. When I run the code below, I was expecting to second.flags.checked to be None,...
JNA's user avatar
  • 55
1 vote
1 answer
51 views

Extract all field names from nested dataclasses

I have a dataclass that contains within it another dataclass: @dataclass class A: var_1: str var_2: int @dataclass class B: var_3: float var_4: A I would like to create a list of all ...
Dan Jackson's user avatar
3 votes
1 answer
66 views

How can I dump a Python dataclass to YAML without tags?

I have a nested dataclasses that I would like to convert and save to the yaml format using the PyYaml library. The resultant YAML output contains YAML tags which I would like to remove. I have the ...
otherJL0's user avatar
2 votes
1 answer
60 views

How to make a python dataclass field not allow None values

After learning a little about dataclasses, it seems that a dataclass will always HAVE all the properties you defined. Adding the Optional only means that you don't have to pass a param into the ...
Clay Casper's user avatar
1 vote
2 answers
56 views

Python frozen dataclass with an optional parameter but non-optional field type

I have a dataclass such as this one: @dataclasses.dataclass(frozen=True) class MyClass: my_field: str other_field: str and I have a complicated function for computing a default value for ...
Pastafarianist's user avatar
0 votes
3 answers
380 views

how to convert a dict to a dataclass (reverse of asdict)?

the dataclasses module lets users make a dict from a dataclass reall conveniently, like this: from dataclasses import dataclass, asdict @dataclass class MyDataClass: ''' description of the ...
D.L's user avatar
  • 4,637
0 votes
0 answers
39 views

storing dataclass member declarations into variables

I am calling a get_unit API that returns a json that contains info about a unit. The API supports sending a flag. For now let's say the possible flags are basic, sensors, or last_update and depending ...
Diaa Malek's user avatar
1 vote
1 answer
96 views

Modifying a dataclass object such that only specified elements are overridden

I would like to create a dataclass A with a lot of member elements. This dataclass should not have Optional members to ensure that the full information is available in the object. Then I want to have ...
Ein Google-Nutzer's user avatar
0 votes
1 answer
63 views

Different dataclass object show equal

I have a simple dataclass with 3 member variables. When I create two different objects for the class and check for equality it always comes out True even if the values for the member variables is ...
Vandit Goel's user avatar
0 votes
0 answers
16 views

Why/when would you use field() for a non-callable default?

I'm trying to understand when it is correct to use field(default=x). I understand in a case where the default is callable, it is wrong not to. For instance: @dataclass class SomeClass: obj_content: ...
Zeke Arneodo's user avatar
2 votes
0 answers
73 views

dataclasses use InitVar default to set instance attribute

When you provide a default for an InitVar typed variable in a dataclass, the attribute for that variable is set (actually, for variables that lack a default the attribute seems to be actively deleted ...
Anthon's user avatar
  • 71.3k
1 vote
1 answer
216 views

How can I make mypy work with a custom class decorator similar to dataclass?

I need to generate code for classes in a very similar way dataclasses.dataclass does. In my first version, I wrote something like: def typedrow(cls: type[_T]) -> type[_T]: cls_annotations = cls....
Igor Gatis's user avatar
  • 4,680
-2 votes
2 answers
94 views

Why are these 2 python class instance could equal to each other?

from dataclasses import dataclass @dataclass class ThreeDPoint: x: int | float y = 0.0 z: int | float = 0.0 point_1 = ThreeDPoint(1.0,2) point_3 = ThreeDPoint(1,2) print(point_1 == ...
anonNEWlearner's user avatar
1 vote
1 answer
54 views

error with reversing linked lists in Python

I've been trying to write a code that will reverse the linked list and I think I've got the concept of reversing the linked list down but I cannot put it into code. the ideal outcome should be 4 3 2 1 ...
ewen's user avatar
  • 13
0 votes
1 answer
38 views

How to map a field to different key for serilization and de-serilization with Python dataclass

I want to serialize and de-serialize some data with a dataclass, but one field in the received data has a different name than the class attribute I want to map it to for example in the data I have : {&...
KZiovas's user avatar
  • 3,825
1 vote
1 answer
106 views

Pydantic validate_arguments on a dataclass

I have a problem with python 3.11, dataclasses and (ancient) pydantic (due to one lib's dependencies, pydantic==1.10) I have a base class, let's call it A and then a few subclasses, like B. Then in ...
bahooo's user avatar
  • 11
1 vote
1 answer
95 views

When making a dataclass, how can I use a custom type for the field objects themselves?

I'm writing a library that works a lot like dataclass but with some additional functionality. Obviously I want to reuse dataclass as much as possible, but for my added functionality, I'd like to ...
J E K's user avatar
  • 154
0 votes
1 answer
23 views

Creating a custom Python type from existing dataclass / pydandic class

I have a kind of standard response format I want to apply to all my fastAPI responses. For this example, we'll talk about something like this: @dataclass class Response status: str = "OK"...
GuruYaya's user avatar
  • 565
0 votes
0 answers
34 views

Strictly Convert JSON dict to dataclass with enums at runtime

So, this actually does work: from dataclasses import dataclass from enum import Enum from typing import Any, TypeVar from pydantic import TypeAdapter, parse_obj_as T = TypeVar('T') def ...
Garrett's user avatar
  • 4,017
4 votes
0 answers
114 views

Type hinting Python dataclasses subclass without redefining default value

When using keyword only dataclasses to define fields of a base class that are inherited by subclasses, how should the fields be type hinted in the subclasses to denote that the fields have a limited ...
gratz's user avatar
  • 1,546
0 votes
0 answers
28 views

Subclassing a dataclass with a constructor setting some parameter of the parent class to a default value

I have a parent dataclass, e.g. @dataclass class A: a = 'a' b = 'b' c = 'c' I want to create a subclass B of A whose constructor takes elements (b,c,d,e), but automatically sets a to 'aa'....
guigux's user avatar
  • 113
0 votes
0 answers
113 views

Pydantic dataclass with Field alias triggers pylint E1123 unexpected-keyword-arg

I'm using the dataclasses feature in Pydantic v2.3.0 and I have a dataclass with an aliased field, like so: from pydantic import Field from pydantic.dataclasses import dataclass @dataclass class ...
bjmc's user avatar
  • 3,019
0 votes
1 answer
89 views

In Python, why doesn't dataclasses.asdict work with fields of type dictionary?

Why doesn't dataclasses.asdict work with dictionary values (not keys)? from dataclasses import asdict, dataclass, field @dataclass(order=True, frozen=True, eq=True) class Path: p: tuple[str, ...] ...
Neil G's user avatar
  • 32.3k
0 votes
0 answers
69 views

Combining Inheritance and dataclass

I would like a decorator for a class that will Add dataclass-ness Inherits a superclass mypy identifies So far, below was my solution. import dataclass as dc # An example superclass class Base: ...
Inyoung Kim 김인영's user avatar
0 votes
0 answers
128 views

How to create reusable code with dataclasses and airflow dags

I'm relatively new to using airflow so please bear with me because I may not ask the question correctly and fresh out of college so this wasn't taught, and I'm a bit confused. I'm working with dbt and ...
kavoisier_n_coding's user avatar
0 votes
1 answer
77 views

How to override the hash function of python data classes? [duplicate]

I am trying to write a base class for python dataclasse with a custom hash function as follows. However, when calling the child class's hash it does not use the custom hash function of the parent ...
motam79's user avatar
  • 3,582
0 votes
2 answers
55 views

How to have half dataclass half dictionary?

There is quite a big, extensive API that works with JSON I am interfacing with. I also have some code that already uses response["Value"] quite extensively. I can create my own wrapper with @...
KamilCuk's user avatar
  • 125k
-1 votes
1 answer
95 views

How to compare large lists of dataclass objects fast in Python

I have two data sources which i must align with each other. One data source is the master and the other one shall mirror the data state of the master. I will call that client as of now. I import the ...
dibade89's user avatar
2 votes
1 answer
53 views

Inner classes can't reference eachother, is there a more Pythonic way?

I want to use inner classes (mainly dataclass and Enums) to keep things encapsulated. They hold data and defines that are only relevant to the main class, so I'd like to keep them inside it. I get the ...
user13722095's user avatar
0 votes
1 answer
52 views

Handle required attributes of parent class(a dataclass) using metaclass or decorators

Suppose class A has n attributes(uninitialized). Now I want a child class that should not directly initialize the parent attributes but should pass a list to a decorator or a metaclass, where only the ...
Nasir Shah's user avatar
  • 5,063
1 vote
1 answer
41 views

why does `json.dumps` yield an empty (stringified) dict when parsing dataclass that subclases `dict`

Why does the following import json from dataclasses import dataclass @dataclass class Foo(dict): bar: Dict example = Foo(bar={'spam': 'eggs'}) json.dumps(example) yield an empty dict in json ...
Alexander McFarlane's user avatar
1 vote
0 answers
99 views

define a typeddict from a dataclass

I am implementing a function that builds and returns a (frozen) dataclass. The dataclass definition is public and "official". Internally my implementation I need to do some complex logic to ...
Vito De Tullio's user avatar
0 votes
1 answer
62 views

Creating a dataclass that generates an instance of another class as a default attribute. How can I satisfy this Pylint warning?

Consider this python script from dataclasses import dataclass, field class ClassA: def __init__(self): pass @dataclass class ClassB: class_a: ClassA = field(default_factory=lambda: ...
DJames's user avatar
  • 591
0 votes
1 answer
61 views

Where are the docs about dataclass fields that have no type hints?

Consider this example of dataclass: from dataclasses import dataclass, asdict @dataclass class Example: typed: str = "a" nontyped = "nt_value" # Now let's make some ...
Alexander C's user avatar
  • 3,717
0 votes
1 answer
37 views

What is the Pythonic way of using a moving x,y coordinate dataclass as a dict key?

from dataclasses import dataclass @dataclass class coordinate: x: int y: int objects = {} pos = coordinate(0, 0) objects[pos] = "A" pos.x += 1 # Changing the current position I ...
Spwack's user avatar
  • 47
1 vote
0 answers
35 views

Subclassing dataclass fails to override default arguments

I'm failing to override a default kwarg. n [13]: from dataclasses import dataclass In [14]: @dataclass ...: class D1: ...: name: str = "foo" ...: class D2(D1): ...: ...
Alex's user avatar
  • 606
0 votes
2 answers
62 views

Should dataclass use fields for attributes with only defaults?

When a python dataclass has a simple attribute that only needs a default value, it can be defined either of these ways. from dataclasses import dataclass, field @dataclass class ExampleClass: x: ...
Adam Hughes's user avatar
  • 15.1k
-3 votes
2 answers
105 views

How to Access a variable inside A dataclass In python?

I'm trying to write A dataclass for my python program , My idea was to use the dataclass as the full database , But I do not know how to access the variable from a dataclass. I'd be glad if Someone ...
KhodeNima's user avatar
8 votes
1 answer
77 views

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 ...
enkryptor's user avatar
  • 1,604
3 votes
0 answers
297 views

Is it possible to statically check pattern matching exhaustiveness for Python dataclasses?

Let suppose we have several dataclasses with the only parent (ABC-class). Next, we have some function which process each case individually via pattern matching: from abc import ABC from dataclasses ...
Evgeniy Slobodkin's user avatar
0 votes
1 answer
176 views

How can I overwrite the default print output of a python dataclass?

Given the InventoryItemexample from the dataclasses documentation. from dataclasses import dataclass @dataclass class InventoryItem: """Class for keeping track of an item in ...
wueli's user avatar
  • 991
1 vote
1 answer
121 views

How to handle generic dataclasses in dataclasses-json?

I'm working on defining a schema for fetching data from an API using dataclasses-json, which is based on Marshmallow. A lot of lists in the schema are wrapped in a nodes field, like this: { "...
M1N3R's user avatar
  • 33

1
2 3 4 5
19