Skip to content

Support built-in sum() on sinter.TaskStats and AnonTaskStats - #1140

Open
davrens101 wants to merge 1 commit into
quantumlib:mainfrom
davrens101:fix-sinter-sum-stats
Open

davrens101 wants to merge 1 commit into
quantumlib:mainfrom
davrens101:fix-sinter-sum-stats

Conversation

@davrens101

Copy link
Copy Markdown

Summary of Changes

When aggregating statistical samples from sinter with Python's built-in sum() (e.g. sum(stats_list)), sum() initializes the accumulator with integer 0 by default.

Previously:

  • AnonTaskStats did not define __radd__, so 0 + anon_stats raised TypeError: unsupported operand type(s) for +: 'int' and 'AnonTaskStats'.
  • TaskStats assigned __radd__ = __add__, which attempted self + other. When other was 0, self.__add__(0) returned NotImplemented, causing 0 + task_stats to raise TypeError: unsupported operand type(s) for +: 'int' and 'TaskStats'.

This fix updates __radd__ for both AnonTaskStats and TaskStats to handle other == 0 by returning self, enabling standard Python idioms like sum([s1, s2]).

Before

>>> import sinter
>>> s1 = sinter.AnonTaskStats(shots=10, errors=2)
>>> sum([s1])
TypeError: unsupported operand type(s) for +: 'int' and 'AnonTaskStats'

>>> t1 = sinter.TaskStats(strong_id='1', decoder='pymatching', json_metadata=None, shots=10, errors=2)
>>> sum([t1])
TypeError: unsupported operand type(s) for +: 'int' and 'TaskStats'

After

>>> import sinter
>>> s1 = sinter.AnonTaskStats(shots=10, errors=2)
>>> sum([s1])
sinter.AnonTaskStats(shots=10, errors=2)

>>> t1 = sinter.TaskStats(strong_id='1', decoder='pymatching', json_metadata=None, shots=10, errors=2)
>>> sum([t1])
sinter.TaskStats(strong_id='1', decoder='pymatching', json_metadata=None, shots=10, errors=2)

Tests have been added to verify sum([a, b]) and sum([a]) for both classes.

Signed-off-by: Davis Rens <166565828+davrens101@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant