Choose repr=False for a non-display field
Also published in our Blogger archive.
A dataclass normally generates a representation containing its fields. Marking a field with field(repr=False) excludes that field from the generated repr, while leaving it available on the object and, unless other options change them, in normal construction and comparison behavior.
The example models an API request whose method is useful to show in a diagnostic string, whereas its token is not intended for routine display. The exact representation assertion establishes the output for this small class, and the second assertion shows that repr=False does not delete or redact the actual attribute. Printing a request can therefore be less noisy and less likely to expose an incidental value in a log message.
This option is a display choice, not a security boundary. Other code can read request.token, debuggers may inspect it, and custom formatting or serialization can include it. Avoid treating repr=False as a substitute for secret handling, access controls, or a redaction policy. If an application needs a stable public format, define and test that format explicitly. Dataclasses and this field option are available from Python 3.7. See the official field() parameters.
AI assistance disclosure: this article was drafted with AI assistance and should be adapted to the application’s own data rules.
from dataclasses import dataclass, field
@dataclass
class ApiRequest:
method: str
token: str = field(repr=False)
request = ApiRequest("GET", "token-123")
shown = repr(request)
assert shown == "ApiRequest(method='GET')"
assert "token-123" not in shown
assert request.token == "token-123"
print(shown)
ApiRequest(method='GET')