python-dataclasses

Exporting arbitrary fields in list of dataclass objects to a dict?

Exporting arbitrary fields in list of dataclass objects to a dict? Question: Consider this example: from dataclasses import dataclass, asdict, astuple @dataclass class Player: id: int name: str color: str players = [ Player(123, "Alice", "green"), Player(456, "Bob", "red"), Player(789, "Gemma", "blue"), ] print("players:", players) print("players[0] as dict:", asdict( players[0] ) ) The printout I …

Total answers: 2

Error: Object of type IntervalStrategy is not JSON serializable when add `indent` to verticalize json

Error: Object of type IntervalStrategy is not JSON serializable when add `indent` to verticalize json Question: I want to save a dataclass to a json file and save it, it is ok now without adding paramenter indent. class EnhancedJSONEncoder(json.JSONEncoder): def default(self, o): if dataclasses.is_dataclass(o): return dataclasses.asdict(o) # return super().default(o) model_json = json.dumps(model_args, cls=EnhancedJSONEncoder) model_args is …

Total answers: 2

Dataclasses and slots causing ValueError: 'b' in __slots__ conflicts with class variable

Dataclasses and slots causing ValueError: 'b' in __slots__ conflicts with class variable Question: I don’t understand the error message and also couldn’t find other SO questions and answers helping me to understand this. The MWE is tested with Python 3.9.2. I’m aware that there is a slots=True parameter in Pythons 3.10 dataclasses. But this isn’t …

Total answers: 2

Issue with creation of nested data classes

Issue with creation of nested data classes Question: I’m trying to create nested data classes: from dataclasses import dataclass, field import datetime from typing import List @dataclass class LineItem: displayName: str compareAtPrice: float discountedPrice: float pricing: str = field(init=False) def __post_init__(self): self.pricing = ( "regular" if self.compareAtPrice == self.discountedPrice else "on sale" ) @dataclass class …

Total answers: 1

How to subclass a frozen dataclass using pydantic

How to subclass a frozen dataclass Question: I have inherited the Customer dataclass. This identifies a customer in the customer DB table. Customer is used to produce summary statistics for transactions pertaining to a given customer. It is hashable, hence frozen. I require a SpecialCustomer (a subclass of Customer) it has an extra property: special_property. …

Total answers: 1

Can you modify an object's field every time another field is modified?

Can you modify an object's field every time another field is modified? Question: I have a dataclass that looks like this from dataclasses import dataclass, field @dataclass class Data: name: str | None = None file_friendly_name: str | None = field(default=None, init=False) def __post_init__(self): # If name, automatically create the file_friendly_name if self.name: self.file_friendly_name = …

Total answers: 3

Category and subcategory classes. Need code example

Category and subcategory classes. Need code example Question: I have dict type dataset like [{id, category, parent_id},]. I need create class for parse this dataset and create simple interface to get parents and childrens. I dnt want to invent a wheel, can someone share the code that will help me to implement this task? I …

Total answers: 1

Python: initiated Logger with dataclass field param

Python: initiated Logger with dataclass field param Question: This is my Logger class: import logging import os import datetime class Logger: _logger = None def __new__(cls, user: str, *args, **kwargs): if cls._logger is None: cls._logger = super().__new__(cls, *args, **kwargs) cls._logger = logging.getLogger("crumbs") cls._logger.setLevel(logging.DEBUG) formatter = logging.Formatter(‘[%(asctime)s] [%(levelname)s] [%(filename)s] [%(funcName)s] [%(lineno)d]: %(message)s’) now = datetime.datetime.now() directory_name …

Total answers: 2