asdict() inside .format() in a Python class

Question:

How can I use asdict() method inside .format() in oder to unpack the class attributes.
So that instead of this:

from dataclasses import dataclass, asdict

@dataclass
class InfoMessage():
    training_type: str
    duration: float
    distance: float
    message = 'Training type: {}; Duration: {:.3f} ч.; Distance: {:.3f}'

    def get_message(self) -> str:
        return self.message.format(self.training_type, self.duration, self.distance)

I could write something like this:

@dataclass
class InfoMessage():
    training_type: str
    duration: float
    distance: float
    message = 'Training type: {}; Duration: {:.3f} ч.; Distance: {:.3f}'

    def get_message(self) -> str:
        return self.message.format(asdict().keys())
Asked By: Ian Solomein

||

Answers:

asdict should be called on an instance of a class – self, in this case. Additionally, you don’t need the dict’s keys, you need its values, which you can spread using the * operator:

def get_message(self) -> str:
    return self.message.format(*asdict(self).values())
    # Here --------------------^
Answered By: Mureinik

You can also use **asdict.

@dataclass
class InfoMessage():
    training_type: str
    duration: float
    distance: float
    message = '{Training type}; {Duration:.3f} ч.; {Distance::.3f}'

    def get_message(self) -> str:
        return self.message.format(**asdict(self))
Answered By: Pashevkin_Artem
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.