Skip to content
Advertisement

Tag: python-dataclasses

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

I would like to ignore the default values after calling asdict() so if I call Answer The dataclasses module doesn’t appear to have support for detecting default values in asdict(), however the dataclass-wizard library does — via skip_defaults argument. Example: Further, results show it is close to 2x faster than an approach with dataclasses.adict(). I’ve added benchmark code I used

Python dataclass, one attribute referencing other

Can a dataclass attribute access to the other one? In the above example, one can create a Stock by providing a symbol and the price. If price is not provided, it defaults to a price which we get from some function get_price. Is there a way to reference symbol? This example generates error NameError: name ‘symbol’ is not defined. Answer

Validate dataclass field with custom defined method?

While working with dataclasses, type hints are good but what I’m looking also for is a Validation of passed values (such as string of max length 50, int with upper limit of 100 etc) Is there anyway to validate passed value ? For example, Pydantic has these Validators. I’m looking for something native without adding external libraries. My only solution

Adding dataclass fields dynamically with dacite.from_dict

I am using dacite to transform a Python dictionary into a dataclass. Is there a way to dynamically add fields to a dataclass? Like in the example below, where the dataclass “Parameters” has defined only one timeseries “timeseriesA”, but there might be additional ones (provided through the dictionary) that cannot be declared. In this example, “timeseriesB” will be ignored by

Annotate dataclass class variable with type value

We have a number of dataclasses representing various results with common ancestor Result. Each result then provides its data using its own subclass of ResultData. But we have trouble to annotate the case properly. We came up with following solution: but it stopped working lately with mypy error ClassVar cannot contain type variables [misc]. It is also against PEP 526,

Advertisement