Dataclass comparison methods giving unexpected results

Advertisements I just learnt how dataclasses work and was messing with it, until I ran into a issue with the comparison logic, the first print prints False, even though it should print True as overall of player1 is equal to player2. Here is the code: from dataclasses import dataclass, field @dataclass(order=True) class Player: overall: int… Read More Dataclass comparison methods giving unexpected results

How would I return Python dataclass fields/values that are only defined in __post_init__ in print and pd.Dataframe?

Advertisements TL,DR: I’ve created a dataclass, where not all fields are defined in the init phase, some get added in __post_init__ in relation to an InitVar. When I print the class object, only fields in init gets printed but not those added in __post_init__. This is also true if I convert the object to a… Read More How would I return Python dataclass fields/values that are only defined in __post_init__ in print and pd.Dataframe?

How to override the hash function of python data classes?

Advertisements 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 class. import dataclasses import joblib @dataclasses.dataclass(frozen=True) class HashableDataclass: def __hash__(self): print("Base class hash was called!") fields = dataclasses.fields(self)… Read More How to override the hash function of python data classes?

Why does sort ignore the total ordering methods defined in my class?

Advertisements Given the following class: @functools.total_ordering class Entry: def __init__(self, nr: list[int, int] = None, p: int = 0) -> None: self.nr = nr if nr is not None else [0, 0] self.p = p def __repr__(self) -> str: return f"Entry(nr={self.nr}, p={self.p})" def __eq__(self, other: Entry) -> bool: return (self.nr[0] == other.nr[0] and self.nr[1] >=… Read More Why does sort ignore the total ordering methods defined in my class?

dataclass __annotation__ not working with inheritance

Advertisements I tried this code: from dataclasses import dataclass @dataclass class Data1: d11: str d12: float @dataclass class Data2: d21: str d22: float @dataclass class D3(Data1, Data2): pass print(D3.__annotations__) But the annotations for D3 are only {‘d11’: <class ‘str’>, ‘d12’: <class ‘float’>}. Why does it not include annotations for the Data2 fields? >Solution : __annotations__… Read More dataclass __annotation__ not working with inheritance

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

Advertisements 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 get is: players: [Player(id=123, name=’Alice’, color=’green’), Player(id=456, name=’Bob’, color=’red’), Player(id=789, name=’Gemma’,… Read More Exporting arbitrary fields in list of dataclass objects to a dict?

Issue with creation of nested data classes

Advertisements 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 Order: createdAt: datetime lineItems: List[LineItem] def __post_init__(self):… Read More Issue with creation of nested data classes

How can I restrict this dataclass serialization to only attributes on the base class?

Advertisements Here’s some code: from dataclasses import dataclass from dataclasses_json import dataclass_json @dataclass_json @dataclass class Foo: f: str @dataclass_json @dataclass class Baz(Foo): b: str def full(self): return self.to_dict() # as expected, returns {"f":"f", "b":"b"} def partial(self): return Foo.to_dict(self) # also returns {"f":"f", "b":"b"} # how can I make it just return {"f":"f"}? print(Baz(f="f", b="b").partial()) output:… Read More How can I restrict this dataclass serialization to only attributes on the base class?