Skip to content
Advertisement

Tag: python-dataclasses

Nested python dataclasses with list annotations

python ^3.7. Trying to create nested dataclasses to work with complex json response. I managed to do that with creating dataclass for every level of json and using __post_init_ to set fields as objects of other dataclasses. However that creates a lot of boilerplate code and also, there is no annotation for nested objects. This answer helped me getting closer

Cast a Python class to Numpy Array

Can I cast a python class to a numpy array? In the last step, I would like the to obtain an array np.array([X.x, X.y]). Instead, I get array(X(x=0, y=0), dtype=object). Can I provide method for the dataclass so that the casting works as desired (or overload one of the existing methods of the dataclass)? Answer From docstring of numpy.array we

Abstract dataclass without abstract methods in Python: prohibit instantiation

Even if a class is inherited from ABC, it can still be instantiated unless it contains abstract methods. Having the code below, what is the best way to prevent an Identifier object from being created: Identifier([‘get’, ‘Name’])? Answer You can create a AbstractDataclass class which guarantees this behaviour, and you can use this every time you have a situation like

How does one ignore extra arguments passed to a dataclass?

I’d like to create a config dataclass in order to simplify whitelisting of and access to specific environment variables (typing os.environ[‘VAR_NAME’] is tedious relative to config.VAR_NAME). I therefore need to ignore unused environment variables in my dataclass’s __init__ function, but I don’t know how to extract the default __init__ in order to wrap it with, e.g., a function that also

Data Classes vs typing.NamedTuple primary use cases

Long story short PEP-557 introduced data classes into Python standard library, that basically can fill the same role as collections.namedtuple and typing.NamedTuple. And now I’m wondering how to separate the use cases in which namedtuple is still a better solution. Data classes advantages over NamedTuple Of course, all the credit goes to dataclass if we need: mutable objects inheritance support

Dataclasses and property decorator

I’ve been reading up on Python 3.7’s dataclass as an alternative to namedtuples (what I typically use when having to group data in a structure). I was wondering if dataclass is compatible with the property decorator to define getter and setter functions for the data elements of the dataclass. If so, is this described somewhere? Or are there examples available?

Advertisement