Remove quotes from __repr__ method in Python dataclass decorator

Viewed 83

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):

enter image description 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)
1 Answers

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)
Related