Questions / Quant development, Python correctness
Dataclass ordering follows selected fields
Which object compares smaller under the generated ordering?
from dataclasses import dataclass, field
@dataclass(order=True)
class Job:
priority: int
seq: int = field(compare=False)
a = Job(1, 900)
b = Job(2, 1)
Answer it in the app It's free. You get hints, a second try if you miss, and a follow-up question.
Show the answer and worked solution
Answer: A. a, because only priority participates and 1 < 2.
- The dataclass comparison considers fields in declaration order, excluding fields marked compare=False. Here only priority remains.
- It therefore compares 1 against 2 and finds a smaller than b. The sequence values play no part in this result.
Interview shortcut. compare=False removes a field from ordering.
Takeaway. Field comparison flags define the generated ordering key.
Why the other choices fail
- b, because its sequence is smaller. seq is excluded from comparison. Its smaller value on b cannot override the priority comparison.
- They may compare equal, since seq is ignored. priority still differs: 1 < 2.
- Neither, because compare=False removes the generated ordering. compare=False applies to that field only; order=True still generates ordering using the participating fields.
In the app this has a follow-up where one thing about the setup changes. Try the follow-up.