简体   繁体   中英

Remove quotes from __repr__ method in Python dataclass decorator

When using the dataclass decorator in Python when defining a class, field values which are strings are outputted in the string representation of that object with quotes. See screenshot below from the dataclass documentation (link here ):

在此处输入图像描述

The question is, how do I remove the quotes? In other words, how can I best override the __repr__ method in that comes with the dataclass decorator to make this simple change? As per the example above, I would like the output to look like:

InventoryItem(name=widget, unit_price=3.0, quantity_on_hand=10)

You'd probably have to replace the __repr__ implementation. For example:

from dataclasses import dataclass, _FIELD, _recursive_repr


@dataclass
class InventoryItem:

    name: str
    unit_price: float
    quantity_on_hand: int

    @_recursive_repr
    def __repr__(self):
        # only get fields that actually exist and want to be shown in a repr
        fields = [k for k, v in self.__dataclass_fields__.items() if v._field_type is _FIELD and v.repr]
        return (
            self.__class__.__qualname__
            + "("
            # fetch fields by name, and return their repr - except if they are strings
            + ", ".join(f"{k}={getattr(self, k)}" if issubclass(type(k), str) else f"{k}={getattr(self, k)!r}" for k in fields)
            + ")"
        )


item = InventoryItem(name='widget', unit_price=3.0, quantity_on_hand=10)
print(item)

Result:

InventoryItem(name=widget, unit_price=3.0, quantity_on_hand=10)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM