Skip to content

dyce.r package reference

Experimental

This package is an attempt to provide primitives for producing weighted randomized rolls without the overhead of enumeration. Rolls can be inspected to understand how specific values are derived. It should be considered experimental. Be warned that future release may introduce incompatibilities or remove this package altogether. Feedback, suggestions, and contributions are welcome and appreciated.

Roller class hierarchy

Roller class hierarchy

R

Experimental

This class (and its descendants) should be considered experimental and may change or disappear in future versions.

Where H objects and P objects are used primarily for enumerating weighted outcomes, R objects represent rollers. More specifically, they are immutable nodes assembled in tree-like structures to represent calculations. Unlike H objects or P objects, rollers generate rolls that conform to weighted outcomes without engaging in computationally expensive enumeration. Roller trees are typically composed from various R class methods and operators as well as arithmetic operations.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
>>> from dyce import H, P, R
>>> d6 = H(6)
>>> r_d6 = R.from_value(d6) ; r_d6
ValueRoller(value=H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1}), annotation='')
>>> ((4 * r_d6 + 3) ** 2 % 5).gt(2)
BinarySumOpRoller(
  bin_op=<function R.gt.<locals>._gt at ...>,
  left_source=BinarySumOpRoller(
      bin_op=<built-in function mod>,
      left_source=BinarySumOpRoller(
          bin_op=<built-in function pow>,
          left_source=BinarySumOpRoller(
              bin_op=<built-in function add>,
              left_source=BinarySumOpRoller(
                  bin_op=<built-in function mul>,
                  left_source=ValueRoller(value=4, annotation=''),
                  right_source=ValueRoller(value=H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1}), annotation=''),
                  annotation='',
                ),
              right_source=ValueRoller(value=3, annotation=''),
              annotation='',
            ),
          right_source=ValueRoller(value=2, annotation=''),
          annotation='',
        ),
      right_source=ValueRoller(value=5, annotation=''),
      annotation='',
    ),
  right_source=ValueRoller(value=2, annotation=''),
  annotation='',
)

Info

No optimizations are made when initializing roller trees. They retain their exact structure, even where such structures could be trivially reduced.

1
2
3
4
5
6
7
>>> r_6 = R.from_value(6)
>>> r_6_abs_3 = 3@abs(r_6)
>>> r_6_abs_6_abs_6_abs = R.from_sources(abs(r_6), abs(r_6), abs(r_6))
>>> tuple(r_6_abs_3.roll().outcomes()), tuple(r_6_abs_6_abs_6_abs.roll().outcomes())  # they generate the same rolls
((6, 6, 6), (6, 6, 6))
>>> r_6_abs_3 == r_6_abs_6_abs_6_abs  # and yet, they're different animals
False

This is because the structure itself contains information that might be required by certain contexts. If such information loss is permissible and reduction is desirable, consider using histograms instead.

Roller trees can can be queried via the roll method, which produces Roll objects.

1
2
3
4
5
>>> roll = r_d6.roll()
>>> tuple(roll.outcomes())
(4,)
>>> roll.total()
4
1
2
3
4
>>> d6 + 3
H({4: 1, 5: 1, 6: 1, 7: 1, 8: 1, 9: 1})
>>> (r_d6 + 3).roll().total() in (d6 + 3)
True

Roll objects are much richer than mere sequences of outcomes. They are also tree-like structures that mirror the roller trees used to produce them, capturing references to rollers and the outcomes generated at each node.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
>>> roll = (r_d6 + 3).roll()
>>> roll.total()
8
>>> roll
Roll(
  r=...,
  roll_outcomes=(
    RollOutcome(
      value=8,
      sources=(
        RollOutcome(
          value=5,
          sources=(),
        ),
        RollOutcome(
          value=3,
          sources=(),
        ),
      ),
    ),
  ),
  source_rolls=(
    Roll(
      r=ValueRoller(value=H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1}), annotation=''),
      roll_outcomes=(
        RollOutcome(
          value=5,
          sources=(),
        ),
      ),
      source_rolls=(),
    ),
    Roll(
      r=ValueRoller(value=3, annotation=''),
      roll_outcomes=(
        RollOutcome(
          value=3,
          sources=(),
        ),
      ),
      source_rolls=(),
    ),
  ),
)

Rollers afford optional annotations as a convenience to callers. They are taken into account when comparing roller trees, but otherwise ignored, internally. One use is to capture references to nodes in an abstract syntax tree generated from parsing a proprietary grammar. Any provided annotation can be retrieved using the annotation property. The annotate method can be used to apply an annotation to existing roller.

The R class itself acts as a base from which several computation-specific implementations derive (such as expressing operands like outcomes or histograms, unary operations, binary operations, pools, etc.).

Source code in dyce/r.py
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
class R:
    r"""
    !!! warning "Experimental"

        This class (and its descendants) should be considered experimental and may
        change or disappear in future versions.

    Where [``H`` objects][dyce.h.H] and [``P`` objects][dyce.p.P] are used primarily for
    enumerating weighted outcomes, ``#!python R`` objects represent rollers. More
    specifically, they are immutable nodes assembled in tree-like structures to
    represent calculations. Unlike [``H`` objects][dyce.h.H] or
    [``P`` objects][dyce.p.P], rollers generate rolls that conform to weighted outcomes
    without engaging in computationally expensive enumeration. Roller trees are
    typically composed from various ``#!python R`` class methods and operators as well
    as arithmetic operations.

    ``` python
    >>> from dyce import H, P, R
    >>> d6 = H(6)
    >>> r_d6 = R.from_value(d6) ; r_d6
    ValueRoller(value=H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1}), annotation='')
    >>> ((4 * r_d6 + 3) ** 2 % 5).gt(2)
    BinarySumOpRoller(
      bin_op=<function R.gt.<locals>._gt at ...>,
      left_source=BinarySumOpRoller(
          bin_op=<built-in function mod>,
          left_source=BinarySumOpRoller(
              bin_op=<built-in function pow>,
              left_source=BinarySumOpRoller(
                  bin_op=<built-in function add>,
                  left_source=BinarySumOpRoller(
                      bin_op=<built-in function mul>,
                      left_source=ValueRoller(value=4, annotation=''),
                      right_source=ValueRoller(value=H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1}), annotation=''),
                      annotation='',
                    ),
                  right_source=ValueRoller(value=3, annotation=''),
                  annotation='',
                ),
              right_source=ValueRoller(value=2, annotation=''),
              annotation='',
            ),
          right_source=ValueRoller(value=5, annotation=''),
          annotation='',
        ),
      right_source=ValueRoller(value=2, annotation=''),
      annotation='',
    )

    ```

    !!! info

        No optimizations are made when initializing roller trees. They retain their
        exact structure, even where such structures could be trivially reduced.

        ``` python
        >>> r_6 = R.from_value(6)
        >>> r_6_abs_3 = 3@abs(r_6)
        >>> r_6_abs_6_abs_6_abs = R.from_sources(abs(r_6), abs(r_6), abs(r_6))
        >>> tuple(r_6_abs_3.roll().outcomes()), tuple(r_6_abs_6_abs_6_abs.roll().outcomes())  # they generate the same rolls
        ((6, 6, 6), (6, 6, 6))
        >>> r_6_abs_3 == r_6_abs_6_abs_6_abs  # and yet, they're different animals
        False

        ```

        This is because the structure itself contains information that might be required
        by certain contexts. If such information loss is permissible and
        reduction is desirable, consider using [histograms][dyce.h.H] instead.

    Roller trees can can be queried via the [``roll`` method][dyce.r.R.roll], which
    produces [``Roll`` objects][dyce.r.Roll].

    <!-- BEGIN MONKEY PATCH --
    For deterministic outcomes.

    >>> import random
    >>> from dyce import rng
    >>> rng.RNG = random.Random(1633056380)

      -- END MONKEY PATCH -->

    ``` python
    >>> roll = r_d6.roll()
    >>> tuple(roll.outcomes())
    (4,)
    >>> roll.total()
    4

    ```

    ``` python
    >>> d6 + 3
    H({4: 1, 5: 1, 6: 1, 7: 1, 8: 1, 9: 1})
    >>> (r_d6 + 3).roll().total() in (d6 + 3)
    True

    ```

    [``Roll`` objects][dyce.r.Roll] are much richer than mere sequences of outcomes.
    They are also tree-like structures that mirror the roller trees used to produce
    them, capturing references to rollers and the outcomes generated at each node.

    ``` python
    >>> roll = (r_d6 + 3).roll()
    >>> roll.total()
    8
    >>> roll
    Roll(
      r=...,
      roll_outcomes=(
        RollOutcome(
          value=8,
          sources=(
            RollOutcome(
              value=5,
              sources=(),
            ),
            RollOutcome(
              value=3,
              sources=(),
            ),
          ),
        ),
      ),
      source_rolls=(
        Roll(
          r=ValueRoller(value=H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1}), annotation=''),
          roll_outcomes=(
            RollOutcome(
              value=5,
              sources=(),
            ),
          ),
          source_rolls=(),
        ),
        Roll(
          r=ValueRoller(value=3, annotation=''),
          roll_outcomes=(
            RollOutcome(
              value=3,
              sources=(),
            ),
          ),
          source_rolls=(),
        ),
      ),
    )

    ```

    Rollers afford optional annotations as a convenience to callers. They are taken into
    account when comparing roller trees, but otherwise ignored, internally. One use is
    to capture references to nodes in an abstract syntax tree generated from parsing a
    proprietary grammar. Any provided *annotation* can be retrieved using the
    [``annotation`` property][dyce.r.R.annotation]. The
    [``annotate`` method][dyce.r.R.annotate] can be used to apply an annotation to
    existing roller.

    The ``#!python R`` class itself acts as a base from which several
    computation-specific implementations derive (such as expressing operands like
    outcomes or histograms, unary operations, binary operations, pools, etc.).

    <!-- BEGIN MONKEY PATCH --
    For type-checking docstrings

    >>> from typing import Union
    >>> from dyce.r import PoolRoller, Roll, RollOutcome, ValueRoller
    >>> which: tuple[Union[int, slice], ...]

      -- END MONKEY PATCH -->
    """
    __slots__: Any = ("_annotation", "_sources")

    # ---- Initializer -----------------------------------------------------------------

    @experimental
    @beartype
    def __init__(
        self,
        sources: Iterable[_SourceT] = (),
        annotation: Any = "",
        **kw,
    ):
        r"Initializer."
        super().__init__()
        self._sources = tuple(sources)
        self._annotation = annotation

    # ---- Overrides -------------------------------------------------------------------

    @beartype
    def __repr__(self) -> str:
        return f"""{type(self).__name__}(
  sources=({_seq_repr(self.sources)}),
  annotation={self.annotation!r},
)"""

    @beartype
    def __eq__(self, other) -> bool:
        if isinstance(other, R):
            return (
                (isinstance(self, type(other)) or isinstance(other, type(self)))
                and __eq__(self.sources, other.sources)  # order matters
                and __eq__(self.annotation, other.annotation)
            )
        else:
            return super().__eq__(other)

    @beartype
    def __ne__(self, other) -> bool:
        if isinstance(other, R):
            return not __eq__(self, other)
        else:
            return super().__ne__(other)

    @beartype
    def __add__(self, other: _ROperandT) -> "BinarySumOpRoller":
        try:
            return self.map(__add__, other)
        except NotImplementedError:
            return NotImplemented

    @beartype
    def __radd__(self, other: RealLike) -> "BinarySumOpRoller":
        try:
            return self.rmap(other, __add__)
        except NotImplementedError:
            return NotImplemented

    @beartype
    def __sub__(self, other: _ROperandT) -> "BinarySumOpRoller":
        try:
            return self.map(__sub__, other)
        except NotImplementedError:
            return NotImplemented

    @beartype
    def __rsub__(self, other: RealLike) -> "BinarySumOpRoller":
        try:
            return self.rmap(other, __sub__)
        except NotImplementedError:
            return NotImplemented

    @beartype
    def __mul__(self, other: _ROperandT) -> "BinarySumOpRoller":
        try:
            return self.map(__mul__, other)
        except NotImplementedError:
            return NotImplemented

    @beartype
    def __rmul__(self, other: RealLike) -> "BinarySumOpRoller":
        try:
            return self.rmap(other, __mul__)
        except NotImplementedError:
            return NotImplemented

    @beartype
    def __matmul__(self, other: SupportsInt) -> "R":
        try:
            other = as_int(other)
        except TypeError:
            return NotImplemented

        if other < 0:
            raise ValueError("argument cannot be negative")
        else:
            return RepeatRoller(other, self)

    @beartype
    def __rmatmul__(self, other: SupportsInt) -> "R":
        return self.__matmul__(other)

    @beartype
    def __truediv__(self, other: _ROperandT) -> "BinarySumOpRoller":
        try:
            return self.map(__truediv__, other)
        except NotImplementedError:
            return NotImplemented

    @beartype
    def __rtruediv__(self, other: RealLike) -> "BinarySumOpRoller":
        try:
            return self.rmap(other, __truediv__)
        except NotImplementedError:
            return NotImplemented

    @beartype
    def __floordiv__(self, other: _ROperandT) -> "BinarySumOpRoller":
        try:
            return self.map(__floordiv__, other)
        except NotImplementedError:
            return NotImplemented

    @beartype
    def __rfloordiv__(self, other: RealLike) -> "BinarySumOpRoller":
        try:
            return self.rmap(other, __floordiv__)
        except NotImplementedError:
            return NotImplemented

    @beartype
    def __mod__(self, other: _ROperandT) -> "BinarySumOpRoller":
        try:
            return self.map(__mod__, other)
        except NotImplementedError:
            return NotImplemented

    @beartype
    def __rmod__(self, other: RealLike) -> "BinarySumOpRoller":
        try:
            return self.rmap(other, __mod__)
        except NotImplementedError:
            return NotImplemented

    @beartype
    def __pow__(self, other: _ROperandT) -> "BinarySumOpRoller":
        try:
            return self.map(__pow__, other)
        except NotImplementedError:
            return NotImplemented

    @beartype
    def __rpow__(self, other: RealLike) -> "BinarySumOpRoller":
        try:
            return self.rmap(other, __pow__)
        except NotImplementedError:
            return NotImplemented

    @beartype
    def __and__(self, other: Union[_SourceT, SupportsInt]) -> "BinarySumOpRoller":
        try:
            if isinstance(other, R):
                return self.map(__and__, other)
            else:
                return self.map(__and__, as_int(other))
        except NotImplementedError:
            return NotImplemented

    @beartype
    def __rand__(self, other: SupportsInt) -> "BinarySumOpRoller":
        try:
            return self.rmap(as_int(other), __and__)
        except NotImplementedError:
            return NotImplemented

    @beartype
    def __xor__(self, other: Union[_SourceT, SupportsInt]) -> "BinarySumOpRoller":
        try:
            if isinstance(other, R):
                return self.map(__xor__, other)
            else:
                return self.map(__xor__, as_int(other))
        except NotImplementedError:
            return NotImplemented

    @beartype
    def __rxor__(self, other: SupportsInt) -> "BinarySumOpRoller":
        try:
            return self.rmap(as_int(other), __xor__)
        except NotImplementedError:
            return NotImplemented

    @beartype
    def __or__(self, other: Union[_SourceT, SupportsInt]) -> "BinarySumOpRoller":
        try:
            if isinstance(other, R):
                return self.map(__or__, other)
            else:
                return self.map(__or__, as_int(other))
        except NotImplementedError:
            return NotImplemented

    @beartype
    def __ror__(self, other: SupportsInt) -> "BinarySumOpRoller":
        try:
            return self.rmap(as_int(other), __or__)
        except NotImplementedError:
            return NotImplemented

    @beartype
    def __neg__(self) -> "UnarySumOpRoller":
        return self.umap(__neg__)

    @beartype
    def __pos__(self) -> "UnarySumOpRoller":
        return self.umap(__pos__)

    @beartype
    def __abs__(self) -> "UnarySumOpRoller":
        return self.umap(__abs__)

    @beartype
    def __invert__(self) -> "UnarySumOpRoller":
        return self.umap(__invert__)

    @abstractmethod
    def roll(self) -> "Roll":
        r"""
        Sub-classes should implement this method to return a new
        [``Roll`` object][dyce.r.Roll] taking into account any
        [sources][dyce.r.R.sources].

        !!! note

            Implementors guarantee that all [``RollOutcome``][dyce.r.RollOutcome]s in
            the returned [``Roll``][dyce.r.Roll] *must* be associated with a roll,
            *including all roll outcomes’ [``sources``][dyce.r.RollOutcome.sources]*.

        <!-- BEGIN MONKEY PATCH --
        For deterministic outcomes.

        >>> import random
        >>> from dyce import rng
        >>> rng.RNG = random.Random(1633403927)

          -- END MONKEY PATCH -->

        !!! tip

            Show that roll outcomes from source rolls are excluded by creating a new
            roll outcome with a value of ``#!python None`` with the excluded roll
            outcome as its source. The
            [``RollOutcome.euthanize``][dyce.r.RollOutcome.euthanize] convenience method
            is provided for this purpose.

            See the section on “[Dropping dice from prior rolls
            …](rollin.md#dropping-dice-from-prior-rolls-keeping-the-best-three-of-3d6-and-1d8)”
            as well as the note in [``Roll.__init__``][dyce.r.Roll.__init__] for
            additional color.

            ``` python
            >>> from itertools import chain
            >>> class AntonChigurhRoller(R):
            ...   h_coin_toss = H((0, 1))
            ...   def roll(self) -> Roll:
            ...     source_rolls = list(self.source_rolls())
            ...     def _roll_outcomes_gen():
            ...       for roll_outcome in chain.from_iterable(source_rolls):
            ...         if roll_outcome.value is None:
            ...           # Omit those already deceased
            ...           continue
            ...         elif self.h_coin_toss.roll():
            ...           # This one lives. Wrap the old outcome in a new one with the same value.
            ...           yield roll_outcome
            ...         else:
            ...           # This one dies here. Wrap the old outcome in a new one with a value of None.
            ...           yield roll_outcome.euthanize()
            ...     return Roll(self, roll_outcomes=_roll_outcomes_gen(), source_rolls=source_rolls)
            >>> ac_r = AntonChigurhRoller(sources=(R.from_value(1), R.from_value(2), R.from_value(3)))
            >>> ac_r.roll()
            Roll(
              r=AntonChigurhRoller(
                sources=(
                  ValueRoller(value=1, annotation=''),
                  ValueRoller(value=2, annotation=''),
                  ValueRoller(value=3, annotation=''),
                ),
                annotation='',
              ),
              roll_outcomes=(
                RollOutcome(
                  value=None,
                  sources=(
                    RollOutcome(
                      value=1,
                      sources=(),
                    ),
                  ),
                ),
                RollOutcome(
                  value=2,
                  sources=(),
                ),
                RollOutcome(
                  value=3,
                  sources=(),
                ),
              ),
              source_rolls=(
                Roll(
                  r=ValueRoller(value=1, annotation=''),
                  roll_outcomes=(
                    RollOutcome(
                      value=1,
                      sources=(),
                    ),
                  ),
                  source_rolls=(),
                ),
                Roll(
                  r=ValueRoller(value=2, annotation=''),
                  roll_outcomes=(
                    RollOutcome(
                      value=2,
                      sources=(),
                    ),
                  ),
                  source_rolls=(),
                ),
                Roll(
                  r=ValueRoller(value=3, annotation=''),
                  roll_outcomes=(
                    RollOutcome(
                      value=3,
                      sources=(),
                    ),
                  ),
                  source_rolls=(),
                ),
              ),
            )

            ```
        """
        ...

    # ---- Properties ------------------------------------------------------------------

    @property
    def annotation(self) -> Any:
        r"""
        Any provided annotation.
        """
        return self._annotation

    @property
    def sources(self) -> tuple[_SourceT, ...]:
        r"""
        The roller’s direct sources (if any).
        """
        return self._sources

    # ---- Methods ---------------------------------------------------------------------

    @classmethod
    @beartype
    def from_sources(
        cls,
        *sources: _SourceT,
        annotation: Any = "",
    ) -> "PoolRoller":
        r"""
        Shorthand for ``#!python cls.from_sources_iterable(rs, annotation=annotation)``.

        See the [``from_sources_iterable`` method][dyce.r.R.from_sources_iterable].
        """
        return cls.from_sources_iterable(sources, annotation=annotation)

    @classmethod
    @beartype
    def from_sources_iterable(
        cls,
        sources: Iterable[_SourceT],
        annotation: Any = "",
    ) -> "PoolRoller":
        r"""
        Creates and returns a roller for “pooling” zero or more *sources*.

        <!-- BEGIN MONKEY PATCH --
        For deterministic outcomes.

        >>> import random
        >>> from dyce import rng
        >>> rng.RNG = random.Random(1633056341)

          -- END MONKEY PATCH -->

        ``` python
        >>> r_pool = R.from_sources_iterable(R.from_value(h) for h in (H((1, 2)), H((3, 4)), H((5, 6))))
        >>> roll = r_pool.roll()
        >>> tuple(roll.outcomes())
        (2, 4, 6)
        >>> roll
        Roll(
          r=...,
          roll_outcomes=(
            RollOutcome(
              value=2,
              sources=(),
            ),
            RollOutcome(
              value=4,
              sources=(),
            ),
            RollOutcome(
              value=6,
              sources=(),
            ),
          ),
          source_rolls=...,
        )

        ```
        """
        return PoolRoller(sources, annotation=annotation)

    @classmethod
    @beartype
    def from_value(
        cls,
        value: _ValueT,
        annotation: Any = "",
    ) -> "ValueRoller":
        r"""
        Creates and returns a [``ValueRoller``][dyce.r.ValueRoller] from *value*.

        ``` python
        >>> R.from_value(6)
        ValueRoller(value=6, annotation='')

        ```

        ``` python
        >>> R.from_value(H(6))
        ValueRoller(value=H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1}), annotation='')

        ```

        ``` python
        >>> R.from_value(P(6, 6))
        ValueRoller(value=2@P(H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1})), annotation='')

        ```
        """
        return ValueRoller(value, annotation=annotation)

    @classmethod
    @beartype
    def from_values(
        cls,
        *values: _ValueT,
        annotation: Any = "",
    ) -> "PoolRoller":
        r"""
        Shorthand for ``#!python cls.from_values_iterable(values, annotation=annotation)``.

        See the [``from_values_iterable`` method][dyce.r.R.from_values_iterable].
        """
        return cls.from_values_iterable(values, annotation=annotation)

    @classmethod
    @beartype
    def from_values_iterable(
        cls,
        values: Iterable[_ValueT],
        annotation: Any = "",
    ) -> "PoolRoller":
        r"""
        Shorthand for ``#!python cls.from_sources_iterable((cls.from_value(value) for value
        in values), annotation=annotation)``.

        See the [``from_value``][dyce.r.R.from_value] and
        [``from_sources_iterable``][dyce.r.R.from_sources_iterable] methods.
        """
        return cls.from_sources_iterable(
            (cls.from_value(value) for value in values),
            annotation=annotation,
        )

    @classmethod
    @beartype
    def filter_from_sources(
        cls,
        predicate: _PredicateT,
        *sources: _SourceT,
        annotation: Any = "",
    ) -> "FilterRoller":
        r"""
        Shorthand for ``#!python cls.filter_from_sources_iterable(predicate, sources,
        annotation=annotation)``.

        See the [``filter_from_sources_iterable``
        method][dyce.r.R.filter_from_sources_iterable].
        """
        return cls.filter_from_sources_iterable(
            predicate, sources, annotation=annotation
        )

    @classmethod
    @beartype
    def filter_from_sources_iterable(
        cls,
        predicate: _PredicateT,
        sources: Iterable[_SourceT],
        annotation: Any = "",
    ) -> "FilterRoller":
        r"""
        Creates and returns a [``FilterRoller``][dyce.r.FilterRoller] for applying filterion
        *predicate* to sorted outcomes from *sources*.

        ``` python
        >>> r_filter = R.filter_from_sources_iterable(
        ...   lambda outcome: bool(outcome.is_even().value),
        ...   (R.from_value(i) for i in (5, 4, 6, 3, 7, 2, 8, 1, 9, 0)),
        ... ) ; r_filter
        FilterRoller(
          predicate=<function <lambda> at ...>,
          sources=(
            ValueRoller(value=5, annotation=''),
            ValueRoller(value=4, annotation=''),
            ...,
            ValueRoller(value=9, annotation=''),
            ValueRoller(value=0, annotation=''),
          ),
          annotation='',
        )
        >>> tuple(r_filter.roll().outcomes())
        (4, 6, 2, 8, 0)

        ```
        """
        return FilterRoller(predicate, sources, annotation=annotation)

    @classmethod
    @beartype
    def filter_from_values(
        cls,
        predicate: _PredicateT,
        *values: _ValueT,
        annotation: Any = "",
    ) -> "FilterRoller":
        r"""
        Shorthand for ``#!python cls.filter_from_values_iterable(predicate, values,
        annotation=annotation)``.

        See the
        [``filter_from_values_iterable`` method][dyce.r.R.filter_from_values_iterable].
        """
        return cls.filter_from_values_iterable(predicate, values, annotation=annotation)

    @classmethod
    @beartype
    def filter_from_values_iterable(
        cls,
        predicate: _PredicateT,
        values: Iterable[_ValueT],
        annotation: Any = "",
    ) -> "FilterRoller":
        r"""
        Shorthand for ``#!python cls.filter_from_sources_iterable((cls.from_value(value) for
        value in values), annotation=annotation)``.

        See the [``from_value``][dyce.r.R.from_value] and
        [``filter_from_sources_iterable``][dyce.r.R.filter_from_sources_iterable]
        methods.
        """
        return cls.filter_from_sources_iterable(
            predicate,
            (cls.from_value(value) for value in values),
            annotation=annotation,
        )

    @classmethod
    @beartype
    def select_from_sources(
        cls,
        which: Iterable[_GetItemT],
        *sources: _SourceT,
        annotation: Any = "",
    ) -> "SelectionRoller":
        r"""
        Shorthand for ``#!python cls.select_from_sources_iterable(which, sources,
        annotation=annotation)``.

        See the [``select_from_sources_iterable``
        method][dyce.r.R.select_from_sources_iterable].
        """
        return cls.select_from_sources_iterable(which, sources, annotation=annotation)

    @classmethod
    @beartype
    def select_from_sources_iterable(
        cls,
        which: Iterable[_GetItemT],
        sources: Iterable[_SourceT],
        annotation: Any = "",
    ) -> "SelectionRoller":
        r"""
        Creates and returns a [``SelectionRoller``][dyce.r.SelectionRoller] for applying
        selection *which* to sorted outcomes from *sources*.

        ``` python
        >>> r_select = R.select_from_sources_iterable(
        ...   (0, -1, slice(3, 6), slice(6, 3, -1), -1, 0),
        ...   (R.from_value(i) for i in (5, 4, 6, 3, 7, 2, 8, 1, 9, 0)),
        ... ) ; r_select
        SelectionRoller(
          which=(0, -1, slice(3, 6, None), slice(6, 3, -1), -1, 0),
          sources=(
            ValueRoller(value=5, annotation=''),
            ValueRoller(value=4, annotation=''),
            ...,
            ValueRoller(value=9, annotation=''),
            ValueRoller(value=0, annotation=''),
          ),
          annotation='',
        )
        >>> tuple(r_select.roll().outcomes())
        (0, 9, 3, 4, 5, 6, 5, 4, 9, 0)

        ```
        """
        return SelectionRoller(which, sources, annotation=annotation)

    @classmethod
    @beartype
    def select_from_values(
        cls,
        which: Iterable[_GetItemT],
        *values: _ValueT,
        annotation: Any = "",
    ) -> "SelectionRoller":
        r"""
        Shorthand for ``#!python cls.select_from_values_iterable(which, values,
        annotation=annotation)``.

        See the
        [``select_from_values_iterable`` method][dyce.r.R.select_from_values_iterable].
        """
        return cls.select_from_values_iterable(which, values, annotation=annotation)

    @classmethod
    @beartype
    def select_from_values_iterable(
        cls,
        which: Iterable[_GetItemT],
        values: Iterable[_ValueT],
        annotation: Any = "",
    ) -> "SelectionRoller":
        r"""
        Shorthand for ``#!python cls.select_from_sources_iterable((cls.from_value(value) for
        value in values), annotation=annotation)``.

        See the [``from_value``][dyce.r.R.from_value] and
        [``select_from_sources_iterable``][dyce.r.R.select_from_sources_iterable]
        methods.
        """
        return cls.select_from_sources_iterable(
            which,
            (cls.from_value(value) for value in values),
            annotation=annotation,
        )

    @beartype
    def source_rolls(self) -> Iterator["Roll"]:
        r"""
        Generates new rolls from all [``sources``][dyce.r.R.sources].
        """
        for source in self.sources:
            yield source.roll()

    @beartype
    def annotate(self, annotation: Any = "") -> "R":
        r"""
        Generates a copy of the roller with the desired annotation.

        ``` python
        >>> r_just_the_n_of_us = R.from_value(5, annotation="But I'm 42!") ; r_just_the_n_of_us
        ValueRoller(value=5, annotation="But I'm 42!")
        >>> r_just_the_n_of_us.annotate("I'm a 42-year-old investment banker!")
        ValueRoller(value=5, annotation="I'm a 42-year-old investment banker!")

        ```
        """
        r = copy(self)
        r._annotation = annotation

        return r

    @beartype
    def map(
        self,
        bin_op: _RollOutcomeBinaryOperatorT,
        right_operand: _ROperandT,
        annotation: Any = "",
    ) -> "BinarySumOpRoller":
        r"""
        Creates and returns a [``BinarySumOpRoller``][dyce.r.BinarySumOpRoller] for applying
        *bin_op* to this roller and *right_operand* as its sources. Shorthands exist for
        many arithmetic operators and comparators.

        ``` python
        >>> import operator
        >>> r_bin_op = R.from_value(H(6)).map(operator.__pow__, 2) ; r_bin_op
        BinarySumOpRoller(
          bin_op=<built-in function pow>,
          left_source=ValueRoller(value=H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1}), annotation=''),
          right_source=ValueRoller(value=2, annotation=''),
          annotation='',
        )
        >>> r_bin_op == R.from_value(H(6)) ** 2
        True

        ```
        """
        if isinstance(right_operand, RealLike):
            right_operand = ValueRoller(right_operand)

        if isinstance(right_operand, (R, RollOutcome)):
            return BinarySumOpRoller(bin_op, self, right_operand, annotation=annotation)
        else:
            raise NotImplementedError

    @beartype
    def rmap(
        self,
        # TODO(posita): See <https://github.com/beartype/beartype/issues/152>
        left_operand: Union[RealLike, "RollOutcome"],
        bin_op: _RollOutcomeBinaryOperatorT,
        annotation: Any = "",
    ) -> "BinarySumOpRoller":
        r"""
        Analogous to the [``map`` method][dyce.r.R.map], but where the caller supplies
        *left_operand*.

        ``` python
        >>> import operator
        >>> r_bin_op = R.from_value(H(6)).rmap(2, operator.__pow__) ; r_bin_op
        BinarySumOpRoller(
          bin_op=<built-in function pow>,
          left_source=ValueRoller(value=2, annotation=''),
          right_source=ValueRoller(value=H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1}), annotation=''),
          annotation='',
        )
        >>> r_bin_op == 2 ** R.from_value(H(6))
        True

        ```

        !!! note

            The positions of *left_operand* and *bin_op* are different from
            [``map`` method][dyce.r.R.map]. This is intentional and serves as a reminder
            of operand ordering.
        """
        if isinstance(left_operand, RealLike):
            return BinarySumOpRoller(
                bin_op, ValueRoller(left_operand), self, annotation=annotation
            )
        elif isinstance(left_operand, RollOutcome):
            return BinarySumOpRoller(bin_op, left_operand, self, annotation=annotation)
        else:
            raise NotImplementedError

    @beartype
    def umap(
        self,
        un_op: _RollOutcomeUnaryOperatorT,
        annotation: Any = "",
    ) -> "UnarySumOpRoller":
        r"""
        Creates and returns a [``UnarySumOpRoller``][dyce.r.UnarySumOpRoller] roller for
        applying *un_op* to this roller as its source.

        ``` python
        >>> import operator
        >>> r_un_op = R.from_value(H(6)).umap(operator.__neg__) ; r_un_op
        UnarySumOpRoller(
          un_op=<built-in function neg>,
          source=ValueRoller(value=H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1}), annotation=''),
          annotation='',
        )
        >>> r_un_op == -R.from_value(H(6))
        True

        ```
        """
        return UnarySumOpRoller(un_op, self, annotation=annotation)

    @beartype
    def lt(self, other: _ROperandT) -> "BinarySumOpRoller":
        r"""
        Shorthand for ``#!python self.map(lambda left, right: left.lt(right), other)``.

        See the [``map`` method][dyce.r.R.map].
        """

        def _lt(left_operand: RollOutcome, right_operand: RollOutcome) -> RollOutcome:
            return left_operand.lt(right_operand)

        return self.map(_lt, other)

    @beartype
    def le(self, other: _ROperandT) -> "BinarySumOpRoller":
        r"""
        Shorthand for ``#!python self.map(lambda left, right: left.le(right), other)``.

        See the [``map`` method][dyce.r.R.map].
        """

        def _le(left_operand: RollOutcome, right_operand: RollOutcome) -> RollOutcome:
            return left_operand.le(right_operand)

        return self.map(_le, other)

    @beartype
    def eq(self, other: _ROperandT) -> "BinarySumOpRoller":
        r"""
        Shorthand for ``#!python self.map(lambda left, right: left.eq(right), other)``.

        See the [``map`` method][dyce.r.R.map].
        """

        def _eq(left_operand: RollOutcome, right_operand: RollOutcome) -> RollOutcome:
            return left_operand.eq(right_operand)

        return self.map(_eq, other)

    @beartype
    def ne(self, other: _ROperandT) -> "BinarySumOpRoller":
        r"""
        Shorthand for ``#!python self.map(lambda left, right: left.ne(right), other)``.

        See the [``map`` method][dyce.r.R.map].
        """

        def _ne(left_operand: RollOutcome, right_operand: RollOutcome) -> RollOutcome:
            return left_operand.ne(right_operand)

        return self.map(_ne, other)

    @beartype
    def gt(self, other: _ROperandT) -> "BinarySumOpRoller":
        r"""
        Shorthand for ``#!python self.map(lambda left, right: left.gt(right), other)``.

        See the [``map`` method][dyce.r.R.map].
        """

        def _gt(left_operand: RollOutcome, right_operand: RollOutcome) -> RollOutcome:
            return left_operand.gt(right_operand)

        return self.map(_gt, other)

    @beartype
    def ge(self, other: _ROperandT) -> "BinarySumOpRoller":
        r"""
        Shorthand for ``#!python self.map(lambda left, right: left.ge(right), other)``.

        See the [``map`` method][dyce.r.R.map].
        """

        def _ge(left_operand: RollOutcome, right_operand: RollOutcome) -> RollOutcome:
            return left_operand.ge(right_operand)

        return self.map(_ge, other)

    @beartype
    def is_even(self) -> "UnarySumOpRoller":
        r"""
        Shorthand for: ``#!python self.umap(lambda operand: operand.is_even())``.

        See the [``umap`` method][dyce.r.R.umap].
        """

        def _is_even(operand: RollOutcome) -> RollOutcome:
            return operand.is_even()

        return self.umap(_is_even)

    @beartype
    def is_odd(self) -> "UnarySumOpRoller":
        r"""
        Shorthand for: ``#!python self.umap(lambda operand: operand.is_odd())``.

        See the [``umap`` method][dyce.r.R.umap].
        """

        def _is_odd(operand: RollOutcome) -> RollOutcome:
            return operand.is_odd()

        return self.umap(_is_odd)

    @beartype
    def filter(
        self,
        predicate: _PredicateT,
        annotation: Any = "",
    ) -> "FilterRoller":
        r"""
        Shorthand for ``#!python type(self).filter_from_sources(predicate, self,
        annotation=annotation)``.

        See the [``filter_from_sources`` method][dyce.r.R.filter_from_sources].
        """
        return type(self).filter_from_sources(predicate, self, annotation=annotation)

    @beartype
    def select(
        self,
        *which: _GetItemT,
        annotation: Any = "",
    ) -> "SelectionRoller":
        r"""
        Shorthand for ``#!python self.select_iterable(which, annotation=annotation)``.

        See the [``select_iterable`` method][dyce.r.R.select_iterable].
        """
        return self.select_iterable(which, annotation=annotation)

    @beartype
    def select_iterable(
        self,
        which: Iterable[_GetItemT],
        annotation: Any = "",
    ) -> "SelectionRoller":
        r"""
        Shorthand for ``#!python type(self).select_from_sources(which, self,
        annotation=annotation)``.

        See the [``select_from_sources`` method][dyce.r.R.select_from_sources].
        """
        return type(self).select_from_sources(which, self, annotation=annotation)

__slots__: Any = ('_annotation', '_sources') class-attribute instance-attribute

annotation: Any property

Any provided annotation.

sources: tuple[_SourceT, ...] property

The roller’s direct sources (if any).

__abs__() -> UnarySumOpRoller

Source code in dyce/r.py
486
487
488
@beartype
def __abs__(self) -> "UnarySumOpRoller":
    return self.umap(__abs__)

__add__(other: _ROperandT) -> BinarySumOpRoller

Source code in dyce/r.py
313
314
315
316
317
318
@beartype
def __add__(self, other: _ROperandT) -> "BinarySumOpRoller":
    try:
        return self.map(__add__, other)
    except NotImplementedError:
        return NotImplemented

__and__(other: Union[_SourceT, SupportsInt]) -> BinarySumOpRoller

Source code in dyce/r.py
427
428
429
430
431
432
433
434
435
@beartype
def __and__(self, other: Union[_SourceT, SupportsInt]) -> "BinarySumOpRoller":
    try:
        if isinstance(other, R):
            return self.map(__and__, other)
        else:
            return self.map(__and__, as_int(other))
    except NotImplementedError:
        return NotImplemented

__eq__(other) -> bool

Source code in dyce/r.py
295
296
297
298
299
300
301
302
303
304
@beartype
def __eq__(self, other) -> bool:
    if isinstance(other, R):
        return (
            (isinstance(self, type(other)) or isinstance(other, type(self)))
            and __eq__(self.sources, other.sources)  # order matters
            and __eq__(self.annotation, other.annotation)
        )
    else:
        return super().__eq__(other)

__floordiv__(other: _ROperandT) -> BinarySumOpRoller

Source code in dyce/r.py
385
386
387
388
389
390
@beartype
def __floordiv__(self, other: _ROperandT) -> "BinarySumOpRoller":
    try:
        return self.map(__floordiv__, other)
    except NotImplementedError:
        return NotImplemented

__init__(sources: Iterable[_SourceT] = (), annotation: Any = '', **kw: Any)

Initializer.

Source code in dyce/r.py
273
274
275
276
277
278
279
280
281
282
283
284
@experimental
@beartype
def __init__(
    self,
    sources: Iterable[_SourceT] = (),
    annotation: Any = "",
    **kw,
):
    r"Initializer."
    super().__init__()
    self._sources = tuple(sources)
    self._annotation = annotation

__invert__() -> UnarySumOpRoller

Source code in dyce/r.py
490
491
492
@beartype
def __invert__(self) -> "UnarySumOpRoller":
    return self.umap(__invert__)

__matmul__(other: SupportsInt) -> R

Source code in dyce/r.py
355
356
357
358
359
360
361
362
363
364
365
@beartype
def __matmul__(self, other: SupportsInt) -> "R":
    try:
        other = as_int(other)
    except TypeError:
        return NotImplemented

    if other < 0:
        raise ValueError("argument cannot be negative")
    else:
        return RepeatRoller(other, self)

__mod__(other: _ROperandT) -> BinarySumOpRoller

Source code in dyce/r.py
399
400
401
402
403
404
@beartype
def __mod__(self, other: _ROperandT) -> "BinarySumOpRoller":
    try:
        return self.map(__mod__, other)
    except NotImplementedError:
        return NotImplemented

__mul__(other: _ROperandT) -> BinarySumOpRoller

Source code in dyce/r.py
341
342
343
344
345
346
@beartype
def __mul__(self, other: _ROperandT) -> "BinarySumOpRoller":
    try:
        return self.map(__mul__, other)
    except NotImplementedError:
        return NotImplemented

__ne__(other) -> bool

Source code in dyce/r.py
306
307
308
309
310
311
@beartype
def __ne__(self, other) -> bool:
    if isinstance(other, R):
        return not __eq__(self, other)
    else:
        return super().__ne__(other)

__neg__() -> UnarySumOpRoller

Source code in dyce/r.py
478
479
480
@beartype
def __neg__(self) -> "UnarySumOpRoller":
    return self.umap(__neg__)

__or__(other: Union[_SourceT, SupportsInt]) -> BinarySumOpRoller

Source code in dyce/r.py
461
462
463
464
465
466
467
468
469
@beartype
def __or__(self, other: Union[_SourceT, SupportsInt]) -> "BinarySumOpRoller":
    try:
        if isinstance(other, R):
            return self.map(__or__, other)
        else:
            return self.map(__or__, as_int(other))
    except NotImplementedError:
        return NotImplemented

__pos__() -> UnarySumOpRoller

Source code in dyce/r.py
482
483
484
@beartype
def __pos__(self) -> "UnarySumOpRoller":
    return self.umap(__pos__)

__pow__(other: _ROperandT) -> BinarySumOpRoller

Source code in dyce/r.py
413
414
415
416
417
418
@beartype
def __pow__(self, other: _ROperandT) -> "BinarySumOpRoller":
    try:
        return self.map(__pow__, other)
    except NotImplementedError:
        return NotImplemented

__radd__(other: RealLike) -> BinarySumOpRoller

Source code in dyce/r.py
320
321
322
323
324
325
@beartype
def __radd__(self, other: RealLike) -> "BinarySumOpRoller":
    try:
        return self.rmap(other, __add__)
    except NotImplementedError:
        return NotImplemented

__rand__(other: SupportsInt) -> BinarySumOpRoller

Source code in dyce/r.py
437
438
439
440
441
442
@beartype
def __rand__(self, other: SupportsInt) -> "BinarySumOpRoller":
    try:
        return self.rmap(as_int(other), __and__)
    except NotImplementedError:
        return NotImplemented

__repr__() -> str

Source code in dyce/r.py
288
289
290
291
292
293
    @beartype
    def __repr__(self) -> str:
        return f"""{type(self).__name__}(
  sources=({_seq_repr(self.sources)}),
  annotation={self.annotation!r},
)"""

__rfloordiv__(other: RealLike) -> BinarySumOpRoller

Source code in dyce/r.py
392
393
394
395
396
397
@beartype
def __rfloordiv__(self, other: RealLike) -> "BinarySumOpRoller":
    try:
        return self.rmap(other, __floordiv__)
    except NotImplementedError:
        return NotImplemented

__rmatmul__(other: SupportsInt) -> R

Source code in dyce/r.py
367
368
369
@beartype
def __rmatmul__(self, other: SupportsInt) -> "R":
    return self.__matmul__(other)

__rmod__(other: RealLike) -> BinarySumOpRoller

Source code in dyce/r.py
406
407
408
409
410
411
@beartype
def __rmod__(self, other: RealLike) -> "BinarySumOpRoller":
    try:
        return self.rmap(other, __mod__)
    except NotImplementedError:
        return NotImplemented

__rmul__(other: RealLike) -> BinarySumOpRoller

Source code in dyce/r.py
348
349
350
351
352
353
@beartype
def __rmul__(self, other: RealLike) -> "BinarySumOpRoller":
    try:
        return self.rmap(other, __mul__)
    except NotImplementedError:
        return NotImplemented

__ror__(other: SupportsInt) -> BinarySumOpRoller

Source code in dyce/r.py
471
472
473
474
475
476
@beartype
def __ror__(self, other: SupportsInt) -> "BinarySumOpRoller":
    try:
        return self.rmap(as_int(other), __or__)
    except NotImplementedError:
        return NotImplemented

__rpow__(other: RealLike) -> BinarySumOpRoller

Source code in dyce/r.py
420
421
422
423
424
425
@beartype
def __rpow__(self, other: RealLike) -> "BinarySumOpRoller":
    try:
        return self.rmap(other, __pow__)
    except NotImplementedError:
        return NotImplemented

__rsub__(other: RealLike) -> BinarySumOpRoller

Source code in dyce/r.py
334
335
336
337
338
339
@beartype
def __rsub__(self, other: RealLike) -> "BinarySumOpRoller":
    try:
        return self.rmap(other, __sub__)
    except NotImplementedError:
        return NotImplemented

__rtruediv__(other: RealLike) -> BinarySumOpRoller

Source code in dyce/r.py
378
379
380
381
382
383
@beartype
def __rtruediv__(self, other: RealLike) -> "BinarySumOpRoller":
    try:
        return self.rmap(other, __truediv__)
    except NotImplementedError:
        return NotImplemented

__rxor__(other: SupportsInt) -> BinarySumOpRoller

Source code in dyce/r.py
454
455
456
457
458
459
@beartype
def __rxor__(self, other: SupportsInt) -> "BinarySumOpRoller":
    try:
        return self.rmap(as_int(other), __xor__)
    except NotImplementedError:
        return NotImplemented

__sub__(other: _ROperandT) -> BinarySumOpRoller

Source code in dyce/r.py
327
328
329
330
331
332
@beartype
def __sub__(self, other: _ROperandT) -> "BinarySumOpRoller":
    try:
        return self.map(__sub__, other)
    except NotImplementedError:
        return NotImplemented

__truediv__(other: _ROperandT) -> BinarySumOpRoller

Source code in dyce/r.py
371
372
373
374
375
376
@beartype
def __truediv__(self, other: _ROperandT) -> "BinarySumOpRoller":
    try:
        return self.map(__truediv__, other)
    except NotImplementedError:
        return NotImplemented

__xor__(other: Union[_SourceT, SupportsInt]) -> BinarySumOpRoller

Source code in dyce/r.py
444
445
446
447
448
449
450
451
452
@beartype
def __xor__(self, other: Union[_SourceT, SupportsInt]) -> "BinarySumOpRoller":
    try:
        if isinstance(other, R):
            return self.map(__xor__, other)
        else:
            return self.map(__xor__, as_int(other))
    except NotImplementedError:
        return NotImplemented

annotate(annotation: Any = '') -> R

Generates a copy of the roller with the desired annotation.

1
2
3
4
>>> r_just_the_n_of_us = R.from_value(5, annotation="But I'm 42!") ; r_just_the_n_of_us
ValueRoller(value=5, annotation="But I'm 42!")
>>> r_just_the_n_of_us.annotate("I'm a 42-year-old investment banker!")
ValueRoller(value=5, annotation="I'm a 42-year-old investment banker!")
Source code in dyce/r.py
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
@beartype
def annotate(self, annotation: Any = "") -> "R":
    r"""
    Generates a copy of the roller with the desired annotation.

    ``` python
    >>> r_just_the_n_of_us = R.from_value(5, annotation="But I'm 42!") ; r_just_the_n_of_us
    ValueRoller(value=5, annotation="But I'm 42!")
    >>> r_just_the_n_of_us.annotate("I'm a 42-year-old investment banker!")
    ValueRoller(value=5, annotation="I'm a 42-year-old investment banker!")

    ```
    """
    r = copy(self)
    r._annotation = annotation

    return r

eq(other: _ROperandT) -> BinarySumOpRoller

Shorthand for self.map(lambda left, right: left.eq(right), other).

See the map method.

Source code in dyce/r.py
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
@beartype
def eq(self, other: _ROperandT) -> "BinarySumOpRoller":
    r"""
    Shorthand for ``#!python self.map(lambda left, right: left.eq(right), other)``.

    See the [``map`` method][dyce.r.R.map].
    """

    def _eq(left_operand: RollOutcome, right_operand: RollOutcome) -> RollOutcome:
        return left_operand.eq(right_operand)

    return self.map(_eq, other)

filter(predicate: _PredicateT, annotation: Any = '') -> FilterRoller

Shorthand for type(self).filter_from_sources(predicate, self,annotation=annotation).

See the filter_from_sources method.

Source code in dyce/r.py
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
@beartype
def filter(
    self,
    predicate: _PredicateT,
    annotation: Any = "",
) -> "FilterRoller":
    r"""
    Shorthand for ``#!python type(self).filter_from_sources(predicate, self,
    annotation=annotation)``.

    See the [``filter_from_sources`` method][dyce.r.R.filter_from_sources].
    """
    return type(self).filter_from_sources(predicate, self, annotation=annotation)

filter_from_sources(predicate: _PredicateT, *sources: _SourceT, annotation: Any = '') -> FilterRoller classmethod

Shorthand for cls.filter_from_sources_iterable(predicate, sources,annotation=annotation).

See the filter_from_sources_iterable method.

Source code in dyce/r.py
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
@classmethod
@beartype
def filter_from_sources(
    cls,
    predicate: _PredicateT,
    *sources: _SourceT,
    annotation: Any = "",
) -> "FilterRoller":
    r"""
    Shorthand for ``#!python cls.filter_from_sources_iterable(predicate, sources,
    annotation=annotation)``.

    See the [``filter_from_sources_iterable``
    method][dyce.r.R.filter_from_sources_iterable].
    """
    return cls.filter_from_sources_iterable(
        predicate, sources, annotation=annotation
    )

filter_from_sources_iterable(predicate: _PredicateT, sources: Iterable[_SourceT], annotation: Any = '') -> FilterRoller classmethod

Creates and returns a FilterRoller for applying filterion predicate to sorted outcomes from sources.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
>>> r_filter = R.filter_from_sources_iterable(
...   lambda outcome: bool(outcome.is_even().value),
...   (R.from_value(i) for i in (5, 4, 6, 3, 7, 2, 8, 1, 9, 0)),
... ) ; r_filter
FilterRoller(
  predicate=<function <lambda> at ...>,
  sources=(
    ValueRoller(value=5, annotation=''),
    ValueRoller(value=4, annotation=''),
    ...,
    ValueRoller(value=9, annotation=''),
    ValueRoller(value=0, annotation=''),
  ),
  annotation='',
)
>>> tuple(r_filter.roll().outcomes())
(4, 6, 2, 8, 0)
Source code in dyce/r.py
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
@classmethod
@beartype
def filter_from_sources_iterable(
    cls,
    predicate: _PredicateT,
    sources: Iterable[_SourceT],
    annotation: Any = "",
) -> "FilterRoller":
    r"""
    Creates and returns a [``FilterRoller``][dyce.r.FilterRoller] for applying filterion
    *predicate* to sorted outcomes from *sources*.

    ``` python
    >>> r_filter = R.filter_from_sources_iterable(
    ...   lambda outcome: bool(outcome.is_even().value),
    ...   (R.from_value(i) for i in (5, 4, 6, 3, 7, 2, 8, 1, 9, 0)),
    ... ) ; r_filter
    FilterRoller(
      predicate=<function <lambda> at ...>,
      sources=(
        ValueRoller(value=5, annotation=''),
        ValueRoller(value=4, annotation=''),
        ...,
        ValueRoller(value=9, annotation=''),
        ValueRoller(value=0, annotation=''),
      ),
      annotation='',
    )
    >>> tuple(r_filter.roll().outcomes())
    (4, 6, 2, 8, 0)

    ```
    """
    return FilterRoller(predicate, sources, annotation=annotation)

filter_from_values(predicate: _PredicateT, *values: _ValueT, annotation: Any = '') -> FilterRoller classmethod

Shorthand for cls.filter_from_values_iterable(predicate, values,annotation=annotation).

See the filter_from_values_iterable method.

Source code in dyce/r.py
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
@classmethod
@beartype
def filter_from_values(
    cls,
    predicate: _PredicateT,
    *values: _ValueT,
    annotation: Any = "",
) -> "FilterRoller":
    r"""
    Shorthand for ``#!python cls.filter_from_values_iterable(predicate, values,
    annotation=annotation)``.

    See the
    [``filter_from_values_iterable`` method][dyce.r.R.filter_from_values_iterable].
    """
    return cls.filter_from_values_iterable(predicate, values, annotation=annotation)

filter_from_values_iterable(predicate: _PredicateT, values: Iterable[_ValueT], annotation: Any = '') -> FilterRoller classmethod

Shorthand for cls.filter_from_sources_iterable((cls.from_value(value) forvalue in values), annotation=annotation).

See the from_value and filter_from_sources_iterable methods.

Source code in dyce/r.py
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
@classmethod
@beartype
def filter_from_values_iterable(
    cls,
    predicate: _PredicateT,
    values: Iterable[_ValueT],
    annotation: Any = "",
) -> "FilterRoller":
    r"""
    Shorthand for ``#!python cls.filter_from_sources_iterable((cls.from_value(value) for
    value in values), annotation=annotation)``.

    See the [``from_value``][dyce.r.R.from_value] and
    [``filter_from_sources_iterable``][dyce.r.R.filter_from_sources_iterable]
    methods.
    """
    return cls.filter_from_sources_iterable(
        predicate,
        (cls.from_value(value) for value in values),
        annotation=annotation,
    )

from_sources(*sources: _SourceT, annotation: Any = '') -> PoolRoller classmethod

Shorthand for cls.from_sources_iterable(rs, annotation=annotation).

See the from_sources_iterable method.

Source code in dyce/r.py
633
634
635
636
637
638
639
640
641
642
643
644
645
@classmethod
@beartype
def from_sources(
    cls,
    *sources: _SourceT,
    annotation: Any = "",
) -> "PoolRoller":
    r"""
    Shorthand for ``#!python cls.from_sources_iterable(rs, annotation=annotation)``.

    See the [``from_sources_iterable`` method][dyce.r.R.from_sources_iterable].
    """
    return cls.from_sources_iterable(sources, annotation=annotation)

from_sources_iterable(sources: Iterable[_SourceT], annotation: Any = '') -> PoolRoller classmethod

Creates and returns a roller for “pooling” zero or more sources.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
>>> r_pool = R.from_sources_iterable(R.from_value(h) for h in (H((1, 2)), H((3, 4)), H((5, 6))))
>>> roll = r_pool.roll()
>>> tuple(roll.outcomes())
(2, 4, 6)
>>> roll
Roll(
  r=...,
  roll_outcomes=(
    RollOutcome(
      value=2,
      sources=(),
    ),
    RollOutcome(
      value=4,
      sources=(),
    ),
    RollOutcome(
      value=6,
      sources=(),
    ),
  ),
  source_rolls=...,
)
Source code in dyce/r.py
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
@classmethod
@beartype
def from_sources_iterable(
    cls,
    sources: Iterable[_SourceT],
    annotation: Any = "",
) -> "PoolRoller":
    r"""
    Creates and returns a roller for “pooling” zero or more *sources*.

    <!-- BEGIN MONKEY PATCH --
    For deterministic outcomes.

    >>> import random
    >>> from dyce import rng
    >>> rng.RNG = random.Random(1633056341)

      -- END MONKEY PATCH -->

    ``` python
    >>> r_pool = R.from_sources_iterable(R.from_value(h) for h in (H((1, 2)), H((3, 4)), H((5, 6))))
    >>> roll = r_pool.roll()
    >>> tuple(roll.outcomes())
    (2, 4, 6)
    >>> roll
    Roll(
      r=...,
      roll_outcomes=(
        RollOutcome(
          value=2,
          sources=(),
        ),
        RollOutcome(
          value=4,
          sources=(),
        ),
        RollOutcome(
          value=6,
          sources=(),
        ),
      ),
      source_rolls=...,
    )

    ```
    """
    return PoolRoller(sources, annotation=annotation)

from_value(value: _ValueT, annotation: Any = '') -> ValueRoller classmethod

Creates and returns a ValueRoller from value.

1
2
>>> R.from_value(6)
ValueRoller(value=6, annotation='')
1
2
>>> R.from_value(H(6))
ValueRoller(value=H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1}), annotation='')
1
2
>>> R.from_value(P(6, 6))
ValueRoller(value=2@P(H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1})), annotation='')
Source code in dyce/r.py
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
@classmethod
@beartype
def from_value(
    cls,
    value: _ValueT,
    annotation: Any = "",
) -> "ValueRoller":
    r"""
    Creates and returns a [``ValueRoller``][dyce.r.ValueRoller] from *value*.

    ``` python
    >>> R.from_value(6)
    ValueRoller(value=6, annotation='')

    ```

    ``` python
    >>> R.from_value(H(6))
    ValueRoller(value=H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1}), annotation='')

    ```

    ``` python
    >>> R.from_value(P(6, 6))
    ValueRoller(value=2@P(H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1})), annotation='')

    ```
    """
    return ValueRoller(value, annotation=annotation)

from_values(*values: _ValueT, annotation: Any = '') -> PoolRoller classmethod

Shorthand for cls.from_values_iterable(values, annotation=annotation).

See the from_values_iterable method.

Source code in dyce/r.py
725
726
727
728
729
730
731
732
733
734
735
736
737
@classmethod
@beartype
def from_values(
    cls,
    *values: _ValueT,
    annotation: Any = "",
) -> "PoolRoller":
    r"""
    Shorthand for ``#!python cls.from_values_iterable(values, annotation=annotation)``.

    See the [``from_values_iterable`` method][dyce.r.R.from_values_iterable].
    """
    return cls.from_values_iterable(values, annotation=annotation)

from_values_iterable(values: Iterable[_ValueT], annotation: Any = '') -> PoolRoller classmethod

Shorthand for cls.from_sources_iterable((cls.from_value(value) for valuein values), annotation=annotation).

See the from_value and from_sources_iterable methods.

Source code in dyce/r.py
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
@classmethod
@beartype
def from_values_iterable(
    cls,
    values: Iterable[_ValueT],
    annotation: Any = "",
) -> "PoolRoller":
    r"""
    Shorthand for ``#!python cls.from_sources_iterable((cls.from_value(value) for value
    in values), annotation=annotation)``.

    See the [``from_value``][dyce.r.R.from_value] and
    [``from_sources_iterable``][dyce.r.R.from_sources_iterable] methods.
    """
    return cls.from_sources_iterable(
        (cls.from_value(value) for value in values),
        annotation=annotation,
    )

ge(other: _ROperandT) -> BinarySumOpRoller

Shorthand for self.map(lambda left, right: left.ge(right), other).

See the map method.

Source code in dyce/r.py
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
@beartype
def ge(self, other: _ROperandT) -> "BinarySumOpRoller":
    r"""
    Shorthand for ``#!python self.map(lambda left, right: left.ge(right), other)``.

    See the [``map`` method][dyce.r.R.map].
    """

    def _ge(left_operand: RollOutcome, right_operand: RollOutcome) -> RollOutcome:
        return left_operand.ge(right_operand)

    return self.map(_ge, other)

gt(other: _ROperandT) -> BinarySumOpRoller

Shorthand for self.map(lambda left, right: left.gt(right), other).

See the map method.

Source code in dyce/r.py
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
@beartype
def gt(self, other: _ROperandT) -> "BinarySumOpRoller":
    r"""
    Shorthand for ``#!python self.map(lambda left, right: left.gt(right), other)``.

    See the [``map`` method][dyce.r.R.map].
    """

    def _gt(left_operand: RollOutcome, right_operand: RollOutcome) -> RollOutcome:
        return left_operand.gt(right_operand)

    return self.map(_gt, other)

is_even() -> UnarySumOpRoller

Shorthand for: self.umap(lambda operand: operand.is_even()).

See the umap method.

Source code in dyce/r.py
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
@beartype
def is_even(self) -> "UnarySumOpRoller":
    r"""
    Shorthand for: ``#!python self.umap(lambda operand: operand.is_even())``.

    See the [``umap`` method][dyce.r.R.umap].
    """

    def _is_even(operand: RollOutcome) -> RollOutcome:
        return operand.is_even()

    return self.umap(_is_even)

is_odd() -> UnarySumOpRoller

Shorthand for: self.umap(lambda operand: operand.is_odd()).

See the umap method.

Source code in dyce/r.py
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
@beartype
def is_odd(self) -> "UnarySumOpRoller":
    r"""
    Shorthand for: ``#!python self.umap(lambda operand: operand.is_odd())``.

    See the [``umap`` method][dyce.r.R.umap].
    """

    def _is_odd(operand: RollOutcome) -> RollOutcome:
        return operand.is_odd()

    return self.umap(_is_odd)

le(other: _ROperandT) -> BinarySumOpRoller

Shorthand for self.map(lambda left, right: left.le(right), other).

See the map method.

Source code in dyce/r.py
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
@beartype
def le(self, other: _ROperandT) -> "BinarySumOpRoller":
    r"""
    Shorthand for ``#!python self.map(lambda left, right: left.le(right), other)``.

    See the [``map`` method][dyce.r.R.map].
    """

    def _le(left_operand: RollOutcome, right_operand: RollOutcome) -> RollOutcome:
        return left_operand.le(right_operand)

    return self.map(_le, other)

lt(other: _ROperandT) -> BinarySumOpRoller

Shorthand for self.map(lambda left, right: left.lt(right), other).

See the map method.

Source code in dyce/r.py
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
@beartype
def lt(self, other: _ROperandT) -> "BinarySumOpRoller":
    r"""
    Shorthand for ``#!python self.map(lambda left, right: left.lt(right), other)``.

    See the [``map`` method][dyce.r.R.map].
    """

    def _lt(left_operand: RollOutcome, right_operand: RollOutcome) -> RollOutcome:
        return left_operand.lt(right_operand)

    return self.map(_lt, other)

map(bin_op: _RollOutcomeBinaryOperatorT, right_operand: _ROperandT, annotation: Any = '') -> BinarySumOpRoller

Creates and returns a BinarySumOpRoller for applying bin_op to this roller and right_operand as its sources. Shorthands exist for many arithmetic operators and comparators.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
>>> import operator
>>> r_bin_op = R.from_value(H(6)).map(operator.__pow__, 2) ; r_bin_op
BinarySumOpRoller(
  bin_op=<built-in function pow>,
  left_source=ValueRoller(value=H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1}), annotation=''),
  right_source=ValueRoller(value=2, annotation=''),
  annotation='',
)
>>> r_bin_op == R.from_value(H(6)) ** 2
True
Source code in dyce/r.py
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
@beartype
def map(
    self,
    bin_op: _RollOutcomeBinaryOperatorT,
    right_operand: _ROperandT,
    annotation: Any = "",
) -> "BinarySumOpRoller":
    r"""
    Creates and returns a [``BinarySumOpRoller``][dyce.r.BinarySumOpRoller] for applying
    *bin_op* to this roller and *right_operand* as its sources. Shorthands exist for
    many arithmetic operators and comparators.

    ``` python
    >>> import operator
    >>> r_bin_op = R.from_value(H(6)).map(operator.__pow__, 2) ; r_bin_op
    BinarySumOpRoller(
      bin_op=<built-in function pow>,
      left_source=ValueRoller(value=H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1}), annotation=''),
      right_source=ValueRoller(value=2, annotation=''),
      annotation='',
    )
    >>> r_bin_op == R.from_value(H(6)) ** 2
    True

    ```
    """
    if isinstance(right_operand, RealLike):
        right_operand = ValueRoller(right_operand)

    if isinstance(right_operand, (R, RollOutcome)):
        return BinarySumOpRoller(bin_op, self, right_operand, annotation=annotation)
    else:
        raise NotImplementedError

ne(other: _ROperandT) -> BinarySumOpRoller

Shorthand for self.map(lambda left, right: left.ne(right), other).

See the map method.

Source code in dyce/r.py
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
@beartype
def ne(self, other: _ROperandT) -> "BinarySumOpRoller":
    r"""
    Shorthand for ``#!python self.map(lambda left, right: left.ne(right), other)``.

    See the [``map`` method][dyce.r.R.map].
    """

    def _ne(left_operand: RollOutcome, right_operand: RollOutcome) -> RollOutcome:
        return left_operand.ne(right_operand)

    return self.map(_ne, other)

rmap(left_operand: Union[RealLike, RollOutcome], bin_op: _RollOutcomeBinaryOperatorT, annotation: Any = '') -> BinarySumOpRoller

Analogous to the map method, but where the caller supplies left_operand.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
>>> import operator
>>> r_bin_op = R.from_value(H(6)).rmap(2, operator.__pow__) ; r_bin_op
BinarySumOpRoller(
  bin_op=<built-in function pow>,
  left_source=ValueRoller(value=2, annotation=''),
  right_source=ValueRoller(value=H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1}), annotation=''),
  annotation='',
)
>>> r_bin_op == 2 ** R.from_value(H(6))
True

Note

The positions of left_operand and bin_op are different from map method. This is intentional and serves as a reminder of operand ordering.

Source code in dyce/r.py
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
@beartype
def rmap(
    self,
    # TODO(posita): See <https://github.com/beartype/beartype/issues/152>
    left_operand: Union[RealLike, "RollOutcome"],
    bin_op: _RollOutcomeBinaryOperatorT,
    annotation: Any = "",
) -> "BinarySumOpRoller":
    r"""
    Analogous to the [``map`` method][dyce.r.R.map], but where the caller supplies
    *left_operand*.

    ``` python
    >>> import operator
    >>> r_bin_op = R.from_value(H(6)).rmap(2, operator.__pow__) ; r_bin_op
    BinarySumOpRoller(
      bin_op=<built-in function pow>,
      left_source=ValueRoller(value=2, annotation=''),
      right_source=ValueRoller(value=H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1}), annotation=''),
      annotation='',
    )
    >>> r_bin_op == 2 ** R.from_value(H(6))
    True

    ```

    !!! note

        The positions of *left_operand* and *bin_op* are different from
        [``map`` method][dyce.r.R.map]. This is intentional and serves as a reminder
        of operand ordering.
    """
    if isinstance(left_operand, RealLike):
        return BinarySumOpRoller(
            bin_op, ValueRoller(left_operand), self, annotation=annotation
        )
    elif isinstance(left_operand, RollOutcome):
        return BinarySumOpRoller(bin_op, left_operand, self, annotation=annotation)
    else:
        raise NotImplementedError

roll() -> Roll abstractmethod

Sub-classes should implement this method to return a new Roll object taking into account any sources.

Note

Implementors guarantee that all RollOutcomes in the returned Roll must be associated with a roll, including all roll outcomes’ sources.

Tip

Show that roll outcomes from source rolls are excluded by creating a new roll outcome with a value of None with the excluded roll outcome as its source. The RollOutcome.euthanize convenience method is provided for this purpose.

See the section on “Dropping dice from prior rolls …” as well as the note in Roll.__init__ for additional color.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
>>> from itertools import chain
>>> class AntonChigurhRoller(R):
...   h_coin_toss = H((0, 1))
...   def roll(self) -> Roll:
...     source_rolls = list(self.source_rolls())
...     def _roll_outcomes_gen():
...       for roll_outcome in chain.from_iterable(source_rolls):
...         if roll_outcome.value is None:
...           # Omit those already deceased
...           continue
...         elif self.h_coin_toss.roll():
...           # This one lives. Wrap the old outcome in a new one with the same value.
...           yield roll_outcome
...         else:
...           # This one dies here. Wrap the old outcome in a new one with a value of None.
...           yield roll_outcome.euthanize()
...     return Roll(self, roll_outcomes=_roll_outcomes_gen(), source_rolls=source_rolls)
>>> ac_r = AntonChigurhRoller(sources=(R.from_value(1), R.from_value(2), R.from_value(3)))
>>> ac_r.roll()
Roll(
  r=AntonChigurhRoller(
    sources=(
      ValueRoller(value=1, annotation=''),
      ValueRoller(value=2, annotation=''),
      ValueRoller(value=3, annotation=''),
    ),
    annotation='',
  ),
  roll_outcomes=(
    RollOutcome(
      value=None,
      sources=(
        RollOutcome(
          value=1,
          sources=(),
        ),
      ),
    ),
    RollOutcome(
      value=2,
      sources=(),
    ),
    RollOutcome(
      value=3,
      sources=(),
    ),
  ),
  source_rolls=(
    Roll(
      r=ValueRoller(value=1, annotation=''),
      roll_outcomes=(
        RollOutcome(
          value=1,
          sources=(),
        ),
      ),
      source_rolls=(),
    ),
    Roll(
      r=ValueRoller(value=2, annotation=''),
      roll_outcomes=(
        RollOutcome(
          value=2,
          sources=(),
        ),
      ),
      source_rolls=(),
    ),
    Roll(
      r=ValueRoller(value=3, annotation=''),
      roll_outcomes=(
        RollOutcome(
          value=3,
          sources=(),
        ),
      ),
      source_rolls=(),
    ),
  ),
)
Source code in dyce/r.py
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
@abstractmethod
def roll(self) -> "Roll":
    r"""
    Sub-classes should implement this method to return a new
    [``Roll`` object][dyce.r.Roll] taking into account any
    [sources][dyce.r.R.sources].

    !!! note

        Implementors guarantee that all [``RollOutcome``][dyce.r.RollOutcome]s in
        the returned [``Roll``][dyce.r.Roll] *must* be associated with a roll,
        *including all roll outcomes’ [``sources``][dyce.r.RollOutcome.sources]*.

    <!-- BEGIN MONKEY PATCH --
    For deterministic outcomes.

    >>> import random
    >>> from dyce import rng
    >>> rng.RNG = random.Random(1633403927)

      -- END MONKEY PATCH -->

    !!! tip

        Show that roll outcomes from source rolls are excluded by creating a new
        roll outcome with a value of ``#!python None`` with the excluded roll
        outcome as its source. The
        [``RollOutcome.euthanize``][dyce.r.RollOutcome.euthanize] convenience method
        is provided for this purpose.

        See the section on “[Dropping dice from prior rolls
        …](rollin.md#dropping-dice-from-prior-rolls-keeping-the-best-three-of-3d6-and-1d8)”
        as well as the note in [``Roll.__init__``][dyce.r.Roll.__init__] for
        additional color.

        ``` python
        >>> from itertools import chain
        >>> class AntonChigurhRoller(R):
        ...   h_coin_toss = H((0, 1))
        ...   def roll(self) -> Roll:
        ...     source_rolls = list(self.source_rolls())
        ...     def _roll_outcomes_gen():
        ...       for roll_outcome in chain.from_iterable(source_rolls):
        ...         if roll_outcome.value is None:
        ...           # Omit those already deceased
        ...           continue
        ...         elif self.h_coin_toss.roll():
        ...           # This one lives. Wrap the old outcome in a new one with the same value.
        ...           yield roll_outcome
        ...         else:
        ...           # This one dies here. Wrap the old outcome in a new one with a value of None.
        ...           yield roll_outcome.euthanize()
        ...     return Roll(self, roll_outcomes=_roll_outcomes_gen(), source_rolls=source_rolls)
        >>> ac_r = AntonChigurhRoller(sources=(R.from_value(1), R.from_value(2), R.from_value(3)))
        >>> ac_r.roll()
        Roll(
          r=AntonChigurhRoller(
            sources=(
              ValueRoller(value=1, annotation=''),
              ValueRoller(value=2, annotation=''),
              ValueRoller(value=3, annotation=''),
            ),
            annotation='',
          ),
          roll_outcomes=(
            RollOutcome(
              value=None,
              sources=(
                RollOutcome(
                  value=1,
                  sources=(),
                ),
              ),
            ),
            RollOutcome(
              value=2,
              sources=(),
            ),
            RollOutcome(
              value=3,
              sources=(),
            ),
          ),
          source_rolls=(
            Roll(
              r=ValueRoller(value=1, annotation=''),
              roll_outcomes=(
                RollOutcome(
                  value=1,
                  sources=(),
                ),
              ),
              source_rolls=(),
            ),
            Roll(
              r=ValueRoller(value=2, annotation=''),
              roll_outcomes=(
                RollOutcome(
                  value=2,
                  sources=(),
                ),
              ),
              source_rolls=(),
            ),
            Roll(
              r=ValueRoller(value=3, annotation=''),
              roll_outcomes=(
                RollOutcome(
                  value=3,
                  sources=(),
                ),
              ),
              source_rolls=(),
            ),
          ),
        )

        ```
    """
    ...

select(*which: _GetItemT, annotation: Any = '') -> SelectionRoller

Shorthand for self.select_iterable(which, annotation=annotation).

See the select_iterable method.

Source code in dyce/r.py
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
@beartype
def select(
    self,
    *which: _GetItemT,
    annotation: Any = "",
) -> "SelectionRoller":
    r"""
    Shorthand for ``#!python self.select_iterable(which, annotation=annotation)``.

    See the [``select_iterable`` method][dyce.r.R.select_iterable].
    """
    return self.select_iterable(which, annotation=annotation)

select_from_sources(which: Iterable[_GetItemT], *sources: _SourceT, annotation: Any = '') -> SelectionRoller classmethod

Shorthand for cls.select_from_sources_iterable(which, sources,annotation=annotation).

See the select_from_sources_iterable method.

Source code in dyce/r.py
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
@classmethod
@beartype
def select_from_sources(
    cls,
    which: Iterable[_GetItemT],
    *sources: _SourceT,
    annotation: Any = "",
) -> "SelectionRoller":
    r"""
    Shorthand for ``#!python cls.select_from_sources_iterable(which, sources,
    annotation=annotation)``.

    See the [``select_from_sources_iterable``
    method][dyce.r.R.select_from_sources_iterable].
    """
    return cls.select_from_sources_iterable(which, sources, annotation=annotation)

select_from_sources_iterable(which: Iterable[_GetItemT], sources: Iterable[_SourceT], annotation: Any = '') -> SelectionRoller classmethod

Creates and returns a SelectionRoller for applying selection which to sorted outcomes from sources.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
>>> r_select = R.select_from_sources_iterable(
...   (0, -1, slice(3, 6), slice(6, 3, -1), -1, 0),
...   (R.from_value(i) for i in (5, 4, 6, 3, 7, 2, 8, 1, 9, 0)),
... ) ; r_select
SelectionRoller(
  which=(0, -1, slice(3, 6, None), slice(6, 3, -1), -1, 0),
  sources=(
    ValueRoller(value=5, annotation=''),
    ValueRoller(value=4, annotation=''),
    ...,
    ValueRoller(value=9, annotation=''),
    ValueRoller(value=0, annotation=''),
  ),
  annotation='',
)
>>> tuple(r_select.roll().outcomes())
(0, 9, 3, 4, 5, 6, 5, 4, 9, 0)
Source code in dyce/r.py
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
@classmethod
@beartype
def select_from_sources_iterable(
    cls,
    which: Iterable[_GetItemT],
    sources: Iterable[_SourceT],
    annotation: Any = "",
) -> "SelectionRoller":
    r"""
    Creates and returns a [``SelectionRoller``][dyce.r.SelectionRoller] for applying
    selection *which* to sorted outcomes from *sources*.

    ``` python
    >>> r_select = R.select_from_sources_iterable(
    ...   (0, -1, slice(3, 6), slice(6, 3, -1), -1, 0),
    ...   (R.from_value(i) for i in (5, 4, 6, 3, 7, 2, 8, 1, 9, 0)),
    ... ) ; r_select
    SelectionRoller(
      which=(0, -1, slice(3, 6, None), slice(6, 3, -1), -1, 0),
      sources=(
        ValueRoller(value=5, annotation=''),
        ValueRoller(value=4, annotation=''),
        ...,
        ValueRoller(value=9, annotation=''),
        ValueRoller(value=0, annotation=''),
      ),
      annotation='',
    )
    >>> tuple(r_select.roll().outcomes())
    (0, 9, 3, 4, 5, 6, 5, 4, 9, 0)

    ```
    """
    return SelectionRoller(which, sources, annotation=annotation)

select_from_values(which: Iterable[_GetItemT], *values: _ValueT, annotation: Any = '') -> SelectionRoller classmethod

Shorthand for cls.select_from_values_iterable(which, values,annotation=annotation).

See the select_from_values_iterable method.

Source code in dyce/r.py
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
@classmethod
@beartype
def select_from_values(
    cls,
    which: Iterable[_GetItemT],
    *values: _ValueT,
    annotation: Any = "",
) -> "SelectionRoller":
    r"""
    Shorthand for ``#!python cls.select_from_values_iterable(which, values,
    annotation=annotation)``.

    See the
    [``select_from_values_iterable`` method][dyce.r.R.select_from_values_iterable].
    """
    return cls.select_from_values_iterable(which, values, annotation=annotation)

select_from_values_iterable(which: Iterable[_GetItemT], values: Iterable[_ValueT], annotation: Any = '') -> SelectionRoller classmethod

Shorthand for cls.select_from_sources_iterable((cls.from_value(value) forvalue in values), annotation=annotation).

See the from_value and select_from_sources_iterable methods.

Source code in dyce/r.py
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
@classmethod
@beartype
def select_from_values_iterable(
    cls,
    which: Iterable[_GetItemT],
    values: Iterable[_ValueT],
    annotation: Any = "",
) -> "SelectionRoller":
    r"""
    Shorthand for ``#!python cls.select_from_sources_iterable((cls.from_value(value) for
    value in values), annotation=annotation)``.

    See the [``from_value``][dyce.r.R.from_value] and
    [``select_from_sources_iterable``][dyce.r.R.select_from_sources_iterable]
    methods.
    """
    return cls.select_from_sources_iterable(
        which,
        (cls.from_value(value) for value in values),
        annotation=annotation,
    )

select_iterable(which: Iterable[_GetItemT], annotation: Any = '') -> SelectionRoller

Shorthand for type(self).select_from_sources(which, self,annotation=annotation).

See the select_from_sources method.

Source code in dyce/r.py
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
@beartype
def select_iterable(
    self,
    which: Iterable[_GetItemT],
    annotation: Any = "",
) -> "SelectionRoller":
    r"""
    Shorthand for ``#!python type(self).select_from_sources(which, self,
    annotation=annotation)``.

    See the [``select_from_sources`` method][dyce.r.R.select_from_sources].
    """
    return type(self).select_from_sources(which, self, annotation=annotation)

source_rolls() -> Iterator[Roll]

Generates new rolls from all sources.

Source code in dyce/r.py
942
943
944
945
946
947
948
@beartype
def source_rolls(self) -> Iterator["Roll"]:
    r"""
    Generates new rolls from all [``sources``][dyce.r.R.sources].
    """
    for source in self.sources:
        yield source.roll()

umap(un_op: _RollOutcomeUnaryOperatorT, annotation: Any = '') -> UnarySumOpRoller

Creates and returns a UnarySumOpRoller roller for applying un_op to this roller as its source.

1
2
3
4
5
6
7
8
9
>>> import operator
>>> r_un_op = R.from_value(H(6)).umap(operator.__neg__) ; r_un_op
UnarySumOpRoller(
  un_op=<built-in function neg>,
  source=ValueRoller(value=H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1}), annotation=''),
  annotation='',
)
>>> r_un_op == -R.from_value(H(6))
True
Source code in dyce/r.py
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
@beartype
def umap(
    self,
    un_op: _RollOutcomeUnaryOperatorT,
    annotation: Any = "",
) -> "UnarySumOpRoller":
    r"""
    Creates and returns a [``UnarySumOpRoller``][dyce.r.UnarySumOpRoller] roller for
    applying *un_op* to this roller as its source.

    ``` python
    >>> import operator
    >>> r_un_op = R.from_value(H(6)).umap(operator.__neg__) ; r_un_op
    UnarySumOpRoller(
      un_op=<built-in function neg>,
      source=ValueRoller(value=H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1}), annotation=''),
      annotation='',
    )
    >>> r_un_op == -R.from_value(H(6))
    True

    ```
    """
    return UnarySumOpRoller(un_op, self, annotation=annotation)

ValueRoller

Bases: R

A roller whose roll outcomes are derived from scalars, H objects, P objects, RollOutcome objects, or even Roll objects, instead of other source rollers.

Source code in dyce/r.py
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
class ValueRoller(R):
    r"""
    A [roller][dyce.r.R] whose roll outcomes are derived from scalars,
    [``H`` objects][dyce.h.H], [``P`` objects][dyce.p.P],
    [``RollOutcome`` objects][dyce.r.RollOutcome], or even
    [``Roll`` objects][dyce.r.Roll], instead of other source rollers.
    """
    __slots__: Any = ("_value",)

    # ---- Initializer -----------------------------------------------------------------

    @beartype
    def __init__(
        self,
        value: _ValueT,
        annotation: Any = "",
        **kw,
    ):
        r"Initializer."
        super().__init__(sources=(), annotation=annotation, **kw)

        if isinstance(value, P) and not value.is_homogeneous():
            warnings.warn(
                f"using a heterogeneous pool ({value}) is not recommended where traceability is important",
                stacklevel=2,
            )

        self._value = value

    # ---- Overrides -------------------------------------------------------------------

    @beartype
    def __repr__(self) -> str:
        return f"{type(self).__name__}(value={self.value!r}, annotation={self.annotation!r})"

    @beartype
    def roll(self) -> "Roll":
        r""""""
        if isinstance(self.value, P):
            return Roll(
                self,
                roll_outcomes=(RollOutcome(outcome) for outcome in self.value.roll()),
            )
        elif isinstance(self.value, H):
            return Roll(self, roll_outcomes=(RollOutcome(self.value.roll()),))
        elif isinstance(self.value, RealLike):
            return Roll(self, roll_outcomes=(RollOutcome(self.value),))
        else:
            assert False, f"unrecognized value type {self.value!r}"

    # ---- Properties ------------------------------------------------------------------

    @property
    def value(self) -> _ValueT:
        r"""
        The value to be emitted by this roller via its
        [``ValueRoller.roll`` method][dyce.r.ValueRoller.roll].
        """
        return self._value

__slots__: Any = ('_value') class-attribute instance-attribute

value: _ValueT property

The value to be emitted by this roller via its ValueRoller.roll method.

__init__(value: _ValueT, annotation: Any = '', **kw: Any)

Initializer.

Source code in dyce/r.py
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
@beartype
def __init__(
    self,
    value: _ValueT,
    annotation: Any = "",
    **kw,
):
    r"Initializer."
    super().__init__(sources=(), annotation=annotation, **kw)

    if isinstance(value, P) and not value.is_homogeneous():
        warnings.warn(
            f"using a heterogeneous pool ({value}) is not recommended where traceability is important",
            stacklevel=2,
        )

    self._value = value

__repr__() -> str

Source code in dyce/r.py
1245
1246
1247
@beartype
def __repr__(self) -> str:
    return f"{type(self).__name__}(value={self.value!r}, annotation={self.annotation!r})"

roll() -> Roll

Source code in dyce/r.py
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
@beartype
def roll(self) -> "Roll":
    r""""""
    if isinstance(self.value, P):
        return Roll(
            self,
            roll_outcomes=(RollOutcome(outcome) for outcome in self.value.roll()),
        )
    elif isinstance(self.value, H):
        return Roll(self, roll_outcomes=(RollOutcome(self.value.roll()),))
    elif isinstance(self.value, RealLike):
        return Roll(self, roll_outcomes=(RollOutcome(self.value),))
    else:
        assert False, f"unrecognized value type {self.value!r}"

PoolRoller

Bases: R

A roller for rolling flattened “pools” from all sources.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
>>> PoolRoller((
...   PoolRoller((
...     ValueRoller(11),
...     ValueRoller(12),
...   )),
...   PoolRoller((
...     PoolRoller((
...       ValueRoller(211),
...       ValueRoller(212),
...     )),
...     PoolRoller((
...       ValueRoller(221),
...       ValueRoller(222),
...     )),
...   )),
...   ValueRoller(3),
... )).roll()
Roll(
  r=...,
  roll_outcomes=(
    RollOutcome(
      value=11,
      sources=...,
    ),
    RollOutcome(
      value=12,
      sources=...,
    ),
    RollOutcome(
      value=211,
      sources=...,
    ),
    RollOutcome(
      value=212,
      sources=...,
    ),
    RollOutcome(
      value=221,
      sources=...,
    ),
    RollOutcome(
      value=222,
      sources=...,
    ),
    RollOutcome(
      value=3,
      sources=...,
    ),
  ),
  source_rolls=...,
)
Source code in dyce/r.py
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
class PoolRoller(R):
    r"""
    A [roller][dyce.r.R] for rolling flattened “pools” from all *sources*.

    ``` python
    >>> PoolRoller((
    ...   PoolRoller((
    ...     ValueRoller(11),
    ...     ValueRoller(12),
    ...   )),
    ...   PoolRoller((
    ...     PoolRoller((
    ...       ValueRoller(211),
    ...       ValueRoller(212),
    ...     )),
    ...     PoolRoller((
    ...       ValueRoller(221),
    ...       ValueRoller(222),
    ...     )),
    ...   )),
    ...   ValueRoller(3),
    ... )).roll()
    Roll(
      r=...,
      roll_outcomes=(
        RollOutcome(
          value=11,
          sources=...,
        ),
        RollOutcome(
          value=12,
          sources=...,
        ),
        RollOutcome(
          value=211,
          sources=...,
        ),
        RollOutcome(
          value=212,
          sources=...,
        ),
        RollOutcome(
          value=221,
          sources=...,
        ),
        RollOutcome(
          value=222,
          sources=...,
        ),
        RollOutcome(
          value=3,
          sources=...,
        ),
      ),
      source_rolls=...,
    )

    ```
    """
    __slots__: Any = ()

    # ---- Overrides -------------------------------------------------------------------

    @beartype
    def roll(self) -> "Roll":
        r""""""
        source_rolls = list(self.source_rolls())

        return Roll(
            self,
            roll_outcomes=(
                roll_outcome
                for roll_outcome in chain.from_iterable(source_rolls)
                if roll_outcome.value is not None
            ),
            source_rolls=source_rolls,
        )

__slots__: Any = () class-attribute instance-attribute

roll() -> Roll

Source code in dyce/r.py
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
@beartype
def roll(self) -> "Roll":
    r""""""
    source_rolls = list(self.source_rolls())

    return Roll(
        self,
        roll_outcomes=(
            roll_outcome
            for roll_outcome in chain.from_iterable(source_rolls)
            if roll_outcome.value is not None
        ),
        source_rolls=source_rolls,
    )

RepeatRoller

Bases: R

A roller to implement the __matmul__ operator. It is akin to a homogeneous PoolRoller containing n identical sources.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
>>> d20 = H(20)
>>> r_d20 = R.from_value(d20)
>>> r_d20_100 = 100@r_d20 ; r_d20_100
RepeatRoller(
  n=100,
  source=ValueRoller(value=H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1, 8: 1, 9: 1, 10: 1, 11: 1, 12: 1, 13: 1, 14: 1, 15: 1, 16: 1, 17: 1, 18: 1, 19: 1, 20: 1}), annotation=''),
  annotation='',
)
>>> all(outcome in d20 for outcome in r_d20_100.roll().outcomes())
True
Source code in dyce/r.py
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
class RepeatRoller(R):
    r"""
    A [roller][dyce.r.R] to implement the ``#!python __matmul__`` operator. It is akin
    to a homogeneous [``PoolRoller``][dyce.r.PoolRoller] containing *n* identical
    *source*s.

    ``` python
    >>> d20 = H(20)
    >>> r_d20 = R.from_value(d20)
    >>> r_d20_100 = 100@r_d20 ; r_d20_100
    RepeatRoller(
      n=100,
      source=ValueRoller(value=H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1, 8: 1, 9: 1, 10: 1, 11: 1, 12: 1, 13: 1, 14: 1, 15: 1, 16: 1, 17: 1, 18: 1, 19: 1, 20: 1}), annotation=''),
      annotation='',
    )
    >>> all(outcome in d20 for outcome in r_d20_100.roll().outcomes())
    True

    ```
    """
    __slots__: Any = ("_n",)

    # ---- Initializer -----------------------------------------------------------------

    @beartype
    def __init__(
        self,
        n: SupportsInt,
        source: _SourceT,
        annotation: Any = "",
        **kw,
    ):
        r"Initializer."
        super().__init__(sources=(source,), annotation=annotation, **kw)
        self._n = as_int(n)

    # ---- Overrides -------------------------------------------------------------------

    @beartype
    def __repr__(self) -> str:
        (source,) = self.sources

        return f"""{type(self).__name__}(
  n={self.n!r},
  source={indent(repr(source), "  ").strip()},
  annotation={self.annotation!r},
)"""

    @beartype
    def __eq__(self, other) -> bool:
        return super().__eq__(other) and self.n == other.n

    @beartype
    def roll(self) -> "Roll":
        r""""""
        source_rolls: list[Roll] = []

        for _ in range(self.n):
            source_rolls.extend(self.source_rolls())

        return Roll(
            self,
            roll_outcomes=(
                roll_outcome
                for roll_outcome in chain.from_iterable(source_rolls)
                if roll_outcome.value is not None
            ),
            source_rolls=source_rolls,
        )

    # ---- Properties ------------------------------------------------------------------

    @property
    def n(self) -> int:
        r"""
        The number of times to “repeat” the roller’s sole source.
        """
        return self._n

__slots__: Any = ('_n') class-attribute instance-attribute

n: int property

The number of times to “repeat” the roller’s sole source.

__eq__(other) -> bool

Source code in dyce/r.py
1402
1403
1404
@beartype
def __eq__(self, other) -> bool:
    return super().__eq__(other) and self.n == other.n

__init__(n: SupportsInt, source: _SourceT, annotation: Any = '', **kw: Any)

Initializer.

Source code in dyce/r.py
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
@beartype
def __init__(
    self,
    n: SupportsInt,
    source: _SourceT,
    annotation: Any = "",
    **kw,
):
    r"Initializer."
    super().__init__(sources=(source,), annotation=annotation, **kw)
    self._n = as_int(n)

__repr__() -> str

Source code in dyce/r.py
1392
1393
1394
1395
1396
1397
1398
1399
1400
    @beartype
    def __repr__(self) -> str:
        (source,) = self.sources

        return f"""{type(self).__name__}(
  n={self.n!r},
  source={indent(repr(source), "  ").strip()},
  annotation={self.annotation!r},
)"""

roll() -> Roll

Source code in dyce/r.py
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
@beartype
def roll(self) -> "Roll":
    r""""""
    source_rolls: list[Roll] = []

    for _ in range(self.n):
        source_rolls.extend(self.source_rolls())

    return Roll(
        self,
        roll_outcomes=(
            roll_outcome
            for roll_outcome in chain.from_iterable(source_rolls)
            if roll_outcome.value is not None
        ),
        source_rolls=source_rolls,
    )

BasicOpRoller

Bases: R

A roller for applying op to some variation of outcomes from sources. Any RollOutcomes returned by op are used directly in the creation of a new Roll.

Source code in dyce/r.py
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
class BasicOpRoller(R):
    r"""
    A [roller][dyce.r.R] for applying *op* to some variation of outcomes from *sources*.
    Any [``RollOutcome``][dyce.r.RollOutcome]s returned by *op* are used directly in the
    creation of a new [``Roll``][dyce.r.Roll].
    """
    __slots__: Any = ("_op",)

    # ---- Initializer -----------------------------------------------------------------

    @beartype
    def __init__(
        self,
        op: BasicOperatorT,
        sources: Iterable[_SourceT],
        annotation: Any = "",
        **kw,
    ):
        r"Initializer."
        super().__init__(sources=sources, annotation=annotation, **kw)
        self._op = op

    # ---- Overrides -------------------------------------------------------------------

    @beartype
    def __repr__(self) -> str:
        return f"""{type(self).__name__}(
  op={self.op!r},
  sources=({_seq_repr(self.sources)}),
  annotation={self.annotation!r},
)"""

    @beartype
    def __eq__(self, other) -> bool:
        return super().__eq__(other) and (_callable_cmp(self.op, other.op))

    @beartype
    def roll(self) -> "Roll":
        r""""""
        source_rolls = list(self.source_rolls())
        res = self.op(
            self,
            (
                roll_outcome
                for roll_outcome in chain.from_iterable(source_rolls)
                if roll_outcome.value is not None
            ),
        )

        if isinstance(res, RollOutcome):
            roll_outcomes = (res,)
        else:
            roll_outcomes = res  # type: ignore [assignment]  # TODO(posita): WTF?

        return Roll(self, roll_outcomes=roll_outcomes, source_rolls=source_rolls)

    # ---- Properties ------------------------------------------------------------------

    @property
    def op(self) -> BasicOperatorT:
        r"""
        The operator this roller applies to its sources.
        """
        return self._op

__slots__: Any = ('_op') class-attribute instance-attribute

op: BasicOperatorT property

The operator this roller applies to its sources.

__eq__(other) -> bool

Source code in dyce/r.py
1466
1467
1468
@beartype
def __eq__(self, other) -> bool:
    return super().__eq__(other) and (_callable_cmp(self.op, other.op))

__init__(op: BasicOperatorT, sources: Iterable[_SourceT], annotation: Any = '', **kw: Any)

Initializer.

Source code in dyce/r.py
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
@beartype
def __init__(
    self,
    op: BasicOperatorT,
    sources: Iterable[_SourceT],
    annotation: Any = "",
    **kw,
):
    r"Initializer."
    super().__init__(sources=sources, annotation=annotation, **kw)
    self._op = op

__repr__() -> str

Source code in dyce/r.py
1458
1459
1460
1461
1462
1463
1464
    @beartype
    def __repr__(self) -> str:
        return f"""{type(self).__name__}(
  op={self.op!r},
  sources=({_seq_repr(self.sources)}),
  annotation={self.annotation!r},
)"""

roll() -> Roll

Source code in dyce/r.py
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
@beartype
def roll(self) -> "Roll":
    r""""""
    source_rolls = list(self.source_rolls())
    res = self.op(
        self,
        (
            roll_outcome
            for roll_outcome in chain.from_iterable(source_rolls)
            if roll_outcome.value is not None
        ),
    )

    if isinstance(res, RollOutcome):
        roll_outcomes = (res,)
    else:
        roll_outcomes = res  # type: ignore [assignment]  # TODO(posita): WTF?

    return Roll(self, roll_outcomes=roll_outcomes, source_rolls=source_rolls)

NarySumOpRoller

Bases: BasicOpRoller

A BasicOpRoller for applying op to the sum of outcomes grouped by each of sources.

Source code in dyce/r.py
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
class NarySumOpRoller(BasicOpRoller):
    r"""
    A [``BasicOpRoller``][dyce.r.BasicOpRoller] for applying *op* to the sum of outcomes
    grouped by each of *sources*.
    """
    __slots__: Any = ()

    # ---- Overrides -------------------------------------------------------------------

    @beartype
    def roll(self) -> "Roll":
        r""""""
        source_rolls = list(self.source_rolls())

        def _sum_roll_outcomes_by_rolls() -> Iterator[RollOutcome]:
            for source_roll in source_rolls:
                if len(source_roll) == 1 and source_roll[0].value is not None:
                    yield from source_roll
                else:
                    yield RollOutcome(sum(source_roll.outcomes()), sources=source_roll)

        res = self.op(self, _sum_roll_outcomes_by_rolls())

        if isinstance(res, RollOutcome):
            roll_outcomes = (res,)
        else:
            roll_outcomes = res  # type: ignore [assignment]  # TODO(posita): WTF?

        return Roll(self, roll_outcomes=roll_outcomes, source_rolls=source_rolls)

__slots__: Any = () class-attribute instance-attribute

roll() -> Roll

Source code in dyce/r.py
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
@beartype
def roll(self) -> "Roll":
    r""""""
    source_rolls = list(self.source_rolls())

    def _sum_roll_outcomes_by_rolls() -> Iterator[RollOutcome]:
        for source_roll in source_rolls:
            if len(source_roll) == 1 and source_roll[0].value is not None:
                yield from source_roll
            else:
                yield RollOutcome(sum(source_roll.outcomes()), sources=source_roll)

    res = self.op(self, _sum_roll_outcomes_by_rolls())

    if isinstance(res, RollOutcome):
        roll_outcomes = (res,)
    else:
        roll_outcomes = res  # type: ignore [assignment]  # TODO(posita): WTF?

    return Roll(self, roll_outcomes=roll_outcomes, source_rolls=source_rolls)

BinarySumOpRoller

Bases: NarySumOpRoller

An NarySumOpRoller for applying a binary operator bin_op to the sum of all outcomes from its left_source and the sum of all outcomes from its right_source.

Source code in dyce/r.py
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
class BinarySumOpRoller(NarySumOpRoller):
    r"""
    An [``NarySumOpRoller``][dyce.r.NarySumOpRoller] for applying a binary operator
    *bin_op* to the sum of all outcomes from its *left_source* and the sum of all
    outcomes from its *right_source*.
    """
    __slots__: Any = ("_bin_op",)

    # ---- Initializer -----------------------------------------------------------------

    @beartype
    def __init__(
        self,
        bin_op: _RollOutcomeBinaryOperatorT,
        left_source: _SourceT,
        right_source: _SourceT,
        annotation: Any = "",
        **kw,
    ):
        r"Initializer."

        def _op(
            r: R,
            roll_outcomes: Iterable[RollOutcome],
        ) -> Union[RollOutcome, Iterable[RollOutcome]]:
            left_operand, right_operand = roll_outcomes

            return bin_op(left_operand, right_operand)

        super().__init__(
            op=_op, sources=(left_source, right_source), annotation=annotation, **kw
        )
        self._bin_op = bin_op

    # ---- Properties ------------------------------------------------------------------

    @property
    def bin_op(self) -> _RollOutcomeBinaryOperatorT:
        r"""
        The operator this roller applies to its sources.
        """
        return self._bin_op

    # ---- Overrides -------------------------------------------------------------------

    @beartype
    def __repr__(self) -> str:
        def _source_repr(source: _SourceT) -> str:
            return indent(repr(source), "  ").strip()

        left_source, right_source = self.sources

        return f"""{type(self).__name__}(
  bin_op={self.bin_op!r},
  left_source={_source_repr(left_source)},
  right_source={_source_repr(right_source)},
  annotation={self.annotation!r},
)"""

    @beartype
    def __eq__(self, other) -> bool:
        return super().__eq__(other) and (_callable_cmp(self.bin_op, other.bin_op))

__slots__: Any = ('_bin_op') class-attribute instance-attribute

bin_op: _RollOutcomeBinaryOperatorT property

The operator this roller applies to its sources.

__eq__(other) -> bool

Source code in dyce/r.py
1590
1591
1592
@beartype
def __eq__(self, other) -> bool:
    return super().__eq__(other) and (_callable_cmp(self.bin_op, other.bin_op))

__init__(bin_op: _RollOutcomeBinaryOperatorT, left_source: _SourceT, right_source: _SourceT, annotation: Any = '', **kw: Any)

Initializer.

Source code in dyce/r.py
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
@beartype
def __init__(
    self,
    bin_op: _RollOutcomeBinaryOperatorT,
    left_source: _SourceT,
    right_source: _SourceT,
    annotation: Any = "",
    **kw,
):
    r"Initializer."

    def _op(
        r: R,
        roll_outcomes: Iterable[RollOutcome],
    ) -> Union[RollOutcome, Iterable[RollOutcome]]:
        left_operand, right_operand = roll_outcomes

        return bin_op(left_operand, right_operand)

    super().__init__(
        op=_op, sources=(left_source, right_source), annotation=annotation, **kw
    )
    self._bin_op = bin_op

__repr__() -> str

Source code in dyce/r.py
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
    @beartype
    def __repr__(self) -> str:
        def _source_repr(source: _SourceT) -> str:
            return indent(repr(source), "  ").strip()

        left_source, right_source = self.sources

        return f"""{type(self).__name__}(
  bin_op={self.bin_op!r},
  left_source={_source_repr(left_source)},
  right_source={_source_repr(right_source)},
  annotation={self.annotation!r},
)"""

UnarySumOpRoller

Bases: NarySumOpRoller

An NarySumOpRoller for applying a unary operator un_op to the sum of all outcomes from its sole source.

Source code in dyce/r.py
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
class UnarySumOpRoller(NarySumOpRoller):
    r"""
    An [``NarySumOpRoller``][dyce.r.NarySumOpRoller] for applying a unary operator
    *un_op* to the sum of all outcomes from its sole *source*.
    """
    __slots__: Any = ("_un_op",)

    # ---- Initializer -----------------------------------------------------------------

    @beartype
    def __init__(
        self,
        un_op: _RollOutcomeUnaryOperatorT,
        source: _SourceT,
        annotation: Any = "",
        **kw,
    ):
        r"Initializer."

        def _op(
            r: R,
            roll_outcomes: Iterable[RollOutcome],
        ) -> Union[RollOutcome, Iterable[RollOutcome]]:
            (operand,) = roll_outcomes

            return un_op(operand)

        super().__init__(op=_op, sources=(source,), annotation=annotation, **kw)
        self._un_op = un_op

    # ---- Overrides -------------------------------------------------------------------

    @beartype
    def __repr__(self) -> str:
        (source,) = self.sources

        return f"""{type(self).__name__}(
  un_op={self.un_op!r},
  source={indent(repr(source), "  ").strip()},
  annotation={self.annotation!r},
)"""

    @beartype
    def __eq__(self, other) -> bool:
        return super().__eq__(other) and (_callable_cmp(self.un_op, other.un_op))

    # ---- Properties ------------------------------------------------------------------

    @property
    def un_op(self) -> _RollOutcomeUnaryOperatorT:
        r"""
        The operator this roller applies to its sources.
        """
        return self._un_op

__slots__: Any = ('_un_op') class-attribute instance-attribute

un_op: _RollOutcomeUnaryOperatorT property

The operator this roller applies to its sources.

__eq__(other) -> bool

Source code in dyce/r.py
1637
1638
1639
@beartype
def __eq__(self, other) -> bool:
    return super().__eq__(other) and (_callable_cmp(self.un_op, other.un_op))

__init__(un_op: _RollOutcomeUnaryOperatorT, source: _SourceT, annotation: Any = '', **kw: Any)

Initializer.

Source code in dyce/r.py
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
@beartype
def __init__(
    self,
    un_op: _RollOutcomeUnaryOperatorT,
    source: _SourceT,
    annotation: Any = "",
    **kw,
):
    r"Initializer."

    def _op(
        r: R,
        roll_outcomes: Iterable[RollOutcome],
    ) -> Union[RollOutcome, Iterable[RollOutcome]]:
        (operand,) = roll_outcomes

        return un_op(operand)

    super().__init__(op=_op, sources=(source,), annotation=annotation, **kw)
    self._un_op = un_op

__repr__() -> str

Source code in dyce/r.py
1627
1628
1629
1630
1631
1632
1633
1634
1635
    @beartype
    def __repr__(self) -> str:
        (source,) = self.sources

        return f"""{type(self).__name__}(
  un_op={self.un_op!r},
  source={indent(repr(source), "  ").strip()},
  annotation={self.annotation!r},
)"""

SubstitutionRoller

Bases: R

A roller for applying expansion_op to determine when to roll new values up to max_depth times for incorporation via coalesce_mode.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
>>> from dyce.r import SubstitutionRoller
>>> r_d6 = R.from_value(H(6))
>>> r_replace = SubstitutionRoller(
...   lambda outcome: RollOutcome(0) if outcome.value is not None and outcome.value <= 3 else outcome,
...   r_d6,
... )
>>> (2@r_replace).roll()
Roll(
  r=RepeatRoller(
    n=2,
    source=SubstitutionRoller(
      expansion_op=<function <lambda> at ...>,
      source=ValueRoller(value=H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1}), annotation=''),
      coalesce_mode=<CoalesceMode.REPLACE: 1>,
      max_depth=1,
      annotation='',
    ),
    annotation='',
  ),
  roll_outcomes=(
    RollOutcome(
      value=0,
      sources=(
        RollOutcome(
          value=2,
          sources=(),
        ),
      ),
    ),
    RollOutcome(
      value=5,
      sources=(),
    ),
  ),
  source_rolls=(...),
)

See the section on “Filtering and substitution” more examples.

Source code in dyce/r.py
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
class SubstitutionRoller(R):
    r"""
    A [roller][dyce.r.R] for applying *expansion_op* to determine when to roll new
    values up to *max_depth* times for incorporation via *coalesce_mode*.

    <!-- BEGIN MONKEY PATCH --
    For deterministic outcomes.

    >>> import random
    >>> from dyce import rng
    >>> rng.RNG = random.Random(1639580307)

      -- END MONKEY PATCH -->

    ``` python
    >>> from dyce.r import SubstitutionRoller
    >>> r_d6 = R.from_value(H(6))
    >>> r_replace = SubstitutionRoller(
    ...   lambda outcome: RollOutcome(0) if outcome.value is not None and outcome.value <= 3 else outcome,
    ...   r_d6,
    ... )
    >>> (2@r_replace).roll()
    Roll(
      r=RepeatRoller(
        n=2,
        source=SubstitutionRoller(
          expansion_op=<function <lambda> at ...>,
          source=ValueRoller(value=H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1}), annotation=''),
          coalesce_mode=<CoalesceMode.REPLACE: 1>,
          max_depth=1,
          annotation='',
        ),
        annotation='',
      ),
      roll_outcomes=(
        RollOutcome(
          value=0,
          sources=(
            RollOutcome(
              value=2,
              sources=(),
            ),
          ),
        ),
        RollOutcome(
          value=5,
          sources=(),
        ),
      ),
      source_rolls=(...),
    )

    ```

    See the section on “[Filtering and
    substitution](rollin.md#filtering-and-substitution)” more examples.
    """
    __slots__: Any = ("_coalesce_mode", "_expansion_op", "_max_depth")

    # ---- Initializer -----------------------------------------------------------------

    @beartype
    def __init__(
        self,
        expansion_op: _ExpansionOperatorT,
        source: _SourceT,
        coalesce_mode: CoalesceMode = CoalesceMode.REPLACE,
        max_depth: SupportsInt = 1,
        annotation: Any = "",
        **kw,
    ):
        r"Initializer."
        super().__init__(sources=(source,), annotation=annotation, **kw)
        self._expansion_op = expansion_op
        self._coalesce_mode = coalesce_mode
        self._max_depth = as_int(max_depth)

    # ---- Overrides -------------------------------------------------------------------

    @beartype
    def __repr__(self) -> str:
        (source,) = self.sources

        return f"""{type(self).__name__}(
  expansion_op={self.expansion_op!r},
  source={indent(repr(source), "  ").strip()},
  coalesce_mode={self.coalesce_mode!r},
  max_depth={self.max_depth!r},
  annotation={self.annotation!r},
)"""

    @beartype
    def __eq__(self, other) -> bool:
        return (
            super().__eq__(other)
            and _callable_cmp(self.expansion_op, other.expansion_op)
            and self.coalesce_mode == other.coalesce_mode
            and self.max_depth == other.max_depth
        )

    @beartype
    def roll(self) -> "Roll":
        r""""""
        (source_roll,) = self.source_rolls()
        source_rolls: list[Roll] = []

        def _expanded_roll_outcomes(
            roll: Roll,
            depth: int = 0,
        ) -> Iterator[RollOutcome]:
            source_rolls.append(roll)
            roll_outcomes = (
                roll_outcome for roll_outcome in roll if roll_outcome.value is not None
            )

            if depth >= self.max_depth:
                yield from roll_outcomes

                return

            for roll_outcome in roll_outcomes:
                expanded = self.expansion_op(roll_outcome)

                if isinstance(expanded, RollOutcome):
                    if expanded is not roll_outcome:
                        expanded = expanded.adopt((roll_outcome,), CoalesceMode.APPEND)
                        # TODO(posita): Not sure why this is necessary
                        assert isinstance(expanded, RollOutcome)

                    yield expanded
                elif isinstance(expanded, Roll):
                    if self.coalesce_mode == CoalesceMode.REPLACE:
                        yield roll_outcome.euthanize()
                    elif self.coalesce_mode == CoalesceMode.APPEND:
                        yield roll_outcome
                    else:
                        assert (
                            False
                        ), f"unrecognized substitution mode {self.coalesce_mode!r}"

                    expanded_roll = expanded.adopt((roll_outcome,), CoalesceMode.APPEND)
                    yield from _expanded_roll_outcomes(expanded_roll, depth + 1)
                else:
                    assert False, f"unrecognized type for expanded value {expanded!r}"

        return Roll(
            self,
            roll_outcomes=_expanded_roll_outcomes(source_roll),
            source_rolls=source_rolls,
        )

    # ---- Properties ------------------------------------------------------------------

    @property
    def max_depth(self) -> int:
        r"""
        The max number of times this roller will attempt to substitute an outcome satisfying
        its [``expansion_op``][dyce.r.SubstitutionRoller.expansion_op].
        """
        return self._max_depth

    @property
    def expansion_op(self) -> _ExpansionOperatorT:
        r"""
        The expansion operator this roller applies to decide whether to substitute outcomes.
        """
        return self._expansion_op

    @property
    def coalesce_mode(self) -> CoalesceMode:
        r"""
        The coalesce mode this roller uses to incorporate substituted outcomes.
        """
        return self._coalesce_mode

__slots__: Any = ('_coalesce_mode', '_expansion_op', '_max_depth') class-attribute instance-attribute

coalesce_mode: CoalesceMode property

The coalesce mode this roller uses to incorporate substituted outcomes.

expansion_op: _ExpansionOperatorT property

The expansion operator this roller applies to decide whether to substitute outcomes.

max_depth: int property

The max number of times this roller will attempt to substitute an outcome satisfying its expansion_op.

__eq__(other) -> bool

Source code in dyce/r.py
2043
2044
2045
2046
2047
2048
2049
2050
@beartype
def __eq__(self, other) -> bool:
    return (
        super().__eq__(other)
        and _callable_cmp(self.expansion_op, other.expansion_op)
        and self.coalesce_mode == other.coalesce_mode
        and self.max_depth == other.max_depth
    )

__init__(expansion_op: _ExpansionOperatorT, source: _SourceT, coalesce_mode: CoalesceMode = CoalesceMode.REPLACE, max_depth: SupportsInt = 1, annotation: Any = '', **kw: Any)

Initializer.

Source code in dyce/r.py
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
@beartype
def __init__(
    self,
    expansion_op: _ExpansionOperatorT,
    source: _SourceT,
    coalesce_mode: CoalesceMode = CoalesceMode.REPLACE,
    max_depth: SupportsInt = 1,
    annotation: Any = "",
    **kw,
):
    r"Initializer."
    super().__init__(sources=(source,), annotation=annotation, **kw)
    self._expansion_op = expansion_op
    self._coalesce_mode = coalesce_mode
    self._max_depth = as_int(max_depth)

__repr__() -> str

Source code in dyce/r.py
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
    @beartype
    def __repr__(self) -> str:
        (source,) = self.sources

        return f"""{type(self).__name__}(
  expansion_op={self.expansion_op!r},
  source={indent(repr(source), "  ").strip()},
  coalesce_mode={self.coalesce_mode!r},
  max_depth={self.max_depth!r},
  annotation={self.annotation!r},
)"""

roll() -> Roll

Source code in dyce/r.py
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
@beartype
def roll(self) -> "Roll":
    r""""""
    (source_roll,) = self.source_rolls()
    source_rolls: list[Roll] = []

    def _expanded_roll_outcomes(
        roll: Roll,
        depth: int = 0,
    ) -> Iterator[RollOutcome]:
        source_rolls.append(roll)
        roll_outcomes = (
            roll_outcome for roll_outcome in roll if roll_outcome.value is not None
        )

        if depth >= self.max_depth:
            yield from roll_outcomes

            return

        for roll_outcome in roll_outcomes:
            expanded = self.expansion_op(roll_outcome)

            if isinstance(expanded, RollOutcome):
                if expanded is not roll_outcome:
                    expanded = expanded.adopt((roll_outcome,), CoalesceMode.APPEND)
                    # TODO(posita): Not sure why this is necessary
                    assert isinstance(expanded, RollOutcome)

                yield expanded
            elif isinstance(expanded, Roll):
                if self.coalesce_mode == CoalesceMode.REPLACE:
                    yield roll_outcome.euthanize()
                elif self.coalesce_mode == CoalesceMode.APPEND:
                    yield roll_outcome
                else:
                    assert (
                        False
                    ), f"unrecognized substitution mode {self.coalesce_mode!r}"

                expanded_roll = expanded.adopt((roll_outcome,), CoalesceMode.APPEND)
                yield from _expanded_roll_outcomes(expanded_roll, depth + 1)
            else:
                assert False, f"unrecognized type for expanded value {expanded!r}"

    return Roll(
        self,
        roll_outcomes=_expanded_roll_outcomes(source_roll),
        source_rolls=source_rolls,
    )

FilterRoller

Bases: R

A roller for applying predicate to filter outcomes its sources.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
>>> r_d6 = R.from_value(H(6))
>>> filter_r = (2@r_d6).filter(
...   lambda outcome: outcome.value is not None and outcome.value > 3,  # type: ignore [operator]
... )
>>> (filter_r).roll()
Roll(
  r=FilterRoller(
    predicate=<function <lambda> at ...>,
    sources=(
      RepeatRoller(
        n=2,
        source=ValueRoller(value=H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1}), annotation=''),
        annotation='',
      ),
    ),
    annotation='',
  ),
  roll_outcomes=(
    RollOutcome(
      value=None,
      sources=(
        RollOutcome(
          value=2,
          sources=(),
        ),
      ),
    ),
    RollOutcome(
      value=5,
      sources=(),
    ),
  ),
  source_rolls=(
    Roll(
      r=RepeatRoller(
        n=2,
        source=ValueRoller(value=H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1}), annotation=''),
        annotation='',
      ),
      roll_outcomes=(
        RollOutcome(
          value=2,
          sources=(),
        ),
        RollOutcome(
          value=5,
          sources=(),
        ),
      ),
      source_rolls=(
        Roll(
          r=ValueRoller(value=H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1}), annotation=''),
          roll_outcomes=(
            RollOutcome(
              value=2,
              sources=(),
            ),
          ),
          source_rolls=(),
        ),
        Roll(
          r=ValueRoller(value=H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1}), annotation=''),
          roll_outcomes=(
            RollOutcome(
              value=5,
              sources=(),
            ),
          ),
          source_rolls=(),
        ),
      ),
    ),
  ),
)

See the section on “Filtering and substitution” more examples.

Source code in dyce/r.py
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
class FilterRoller(R):
    r"""
    A [roller][dyce.r.R] for applying *predicate* to filter outcomes its *sources*.

    <!-- BEGIN MONKEY PATCH --
    For deterministic outcomes.

    >>> import random
    >>> from dyce import rng
    >>> rng.RNG = random.Random(1639580307)

      -- END MONKEY PATCH -->

    ``` python
    >>> r_d6 = R.from_value(H(6))
    >>> filter_r = (2@r_d6).filter(
    ...   lambda outcome: outcome.value is not None and outcome.value > 3,  # type: ignore [operator]
    ... )
    >>> (filter_r).roll()
    Roll(
      r=FilterRoller(
        predicate=<function <lambda> at ...>,
        sources=(
          RepeatRoller(
            n=2,
            source=ValueRoller(value=H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1}), annotation=''),
            annotation='',
          ),
        ),
        annotation='',
      ),
      roll_outcomes=(
        RollOutcome(
          value=None,
          sources=(
            RollOutcome(
              value=2,
              sources=(),
            ),
          ),
        ),
        RollOutcome(
          value=5,
          sources=(),
        ),
      ),
      source_rolls=(
        Roll(
          r=RepeatRoller(
            n=2,
            source=ValueRoller(value=H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1}), annotation=''),
            annotation='',
          ),
          roll_outcomes=(
            RollOutcome(
              value=2,
              sources=(),
            ),
            RollOutcome(
              value=5,
              sources=(),
            ),
          ),
          source_rolls=(
            Roll(
              r=ValueRoller(value=H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1}), annotation=''),
              roll_outcomes=(
                RollOutcome(
                  value=2,
                  sources=(),
                ),
              ),
              source_rolls=(),
            ),
            Roll(
              r=ValueRoller(value=H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1}), annotation=''),
              roll_outcomes=(
                RollOutcome(
                  value=5,
                  sources=(),
                ),
              ),
              source_rolls=(),
            ),
          ),
        ),
      ),
    )

    ```

    See the section on “[Filtering and
    substitution](rollin.md#filtering-and-substitution)” more examples.
    """
    __slots__: Any = ("_predicate",)

    # ---- Initializer -----------------------------------------------------------------

    @beartype
    def __init__(
        self,
        predicate: _PredicateT,
        sources: Iterable[R],
        annotation: Any = "",
        **kw,
    ):
        r"Initializer."
        super().__init__(sources=sources, annotation=annotation, **kw)
        self._predicate = predicate

    # ---- Overrides -------------------------------------------------------------------

    @beartype
    def __repr__(self) -> str:
        return f"""{type(self).__name__}(
  predicate={self.predicate!r},
  sources=({_seq_repr(self.sources)}),
  annotation={self.annotation!r},
)"""

    @beartype
    def __eq__(self, other) -> bool:
        return super().__eq__(other) and _callable_cmp(self.predicate, other.predicate)

    @beartype
    def roll(self) -> "Roll":
        r""""""
        source_rolls = list(self.source_rolls())

        def _filtered_roll_outcomes() -> Iterator[RollOutcome]:
            for roll_outcome in chain.from_iterable(source_rolls):
                if roll_outcome.value is not None:
                    if self.predicate(roll_outcome):
                        yield roll_outcome
                    else:
                        yield roll_outcome.euthanize()

        return Roll(
            self, roll_outcomes=_filtered_roll_outcomes(), source_rolls=source_rolls
        )

    # ---- Properties ------------------------------------------------------------------

    @property
    def predicate(self) -> _PredicateT:
        r"""
        The predicate this roller applies to filter its sources.
        """
        return self._predicate

__slots__: Any = ('_predicate') class-attribute instance-attribute

predicate: _PredicateT property

The predicate this roller applies to filter its sources.

__eq__(other) -> bool

Source code in dyce/r.py
1771
1772
1773
@beartype
def __eq__(self, other) -> bool:
    return super().__eq__(other) and _callable_cmp(self.predicate, other.predicate)

__init__(predicate: _PredicateT, sources: Iterable[R], annotation: Any = '', **kw: Any)

Initializer.

Source code in dyce/r.py
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
@beartype
def __init__(
    self,
    predicate: _PredicateT,
    sources: Iterable[R],
    annotation: Any = "",
    **kw,
):
    r"Initializer."
    super().__init__(sources=sources, annotation=annotation, **kw)
    self._predicate = predicate

__repr__() -> str

Source code in dyce/r.py
1763
1764
1765
1766
1767
1768
1769
    @beartype
    def __repr__(self) -> str:
        return f"""{type(self).__name__}(
  predicate={self.predicate!r},
  sources=({_seq_repr(self.sources)}),
  annotation={self.annotation!r},
)"""

roll() -> Roll

Source code in dyce/r.py
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
@beartype
def roll(self) -> "Roll":
    r""""""
    source_rolls = list(self.source_rolls())

    def _filtered_roll_outcomes() -> Iterator[RollOutcome]:
        for roll_outcome in chain.from_iterable(source_rolls):
            if roll_outcome.value is not None:
                if self.predicate(roll_outcome):
                    yield roll_outcome
                else:
                    yield roll_outcome.euthanize()

    return Roll(
        self, roll_outcomes=_filtered_roll_outcomes(), source_rolls=source_rolls
    )

SelectionRoller

Bases: R

A roller for sorting outcomes from its sources and applying a selector which.

Roll outcomes in created rolls are ordered according to the selections which. However, those selections are interpreted as indexes in a sorted view of the source’s roll outcomes.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
>>> r_values = R.from_values(10000, 1, 1000, 10, 100)
>>> outcomes = tuple(r_values.roll().outcomes()) ; outcomes
(10000, 1, 1000, 10, 100)
>>> sorted_outcomes = tuple(sorted(outcomes)) ; sorted_outcomes
(1, 10, 100, 1000, 10000)
>>> which = (3, 1, 3, 2)
>>> tuple(sorted_outcomes[i] for i in which)
(1000, 10, 1000, 100)
>>> r_select = r_values.select_iterable(which) ; r_select
SelectionRoller(
  which=(3, 1, 3, 2),
  sources=(
    PoolRoller(
      sources=(
        ValueRoller(value=10000, annotation=''),
        ValueRoller(value=1, annotation=''),
        ValueRoller(value=1000, annotation=''),
        ValueRoller(value=10, annotation=''),
        ValueRoller(value=100, annotation=''),
      ),
      annotation='',
    ),
  ),
  annotation='',
)
>>> roll = r_select.roll()
>>> tuple(roll.outcomes())
(1000, 10, 1000, 100)
>>> roll
Roll(
  r=...,
  roll_outcomes=(
    RollOutcome(
      value=1000,
      sources=(),
    ),
    RollOutcome(
      value=10,
      sources=(),
    ),
    RollOutcome(
      value=1000,
      sources=(),
    ),
    RollOutcome(
      value=100,
      sources=(),
    ),
    RollOutcome(
      value=None,
      sources=(
        RollOutcome(
          value=1,
          sources=(),
        ),
      ),
    ),
    RollOutcome(
      value=None,
      sources=(
        RollOutcome(
          value=10000,
          sources=(),
        ),
      ),
    ),
  ),
  source_rolls=...,
)
Source code in dyce/r.py
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
class SelectionRoller(R):
    r"""
    A [roller][dyce.r.R] for sorting outcomes from its *sources* and applying a selector
    *which*.

    Roll outcomes in created rolls are ordered according to the selections *which*.
    However, those selections are interpreted as indexes in a *sorted* view of the
    source’s roll outcomes.

    ``` python
    >>> r_values = R.from_values(10000, 1, 1000, 10, 100)
    >>> outcomes = tuple(r_values.roll().outcomes()) ; outcomes
    (10000, 1, 1000, 10, 100)
    >>> sorted_outcomes = tuple(sorted(outcomes)) ; sorted_outcomes
    (1, 10, 100, 1000, 10000)
    >>> which = (3, 1, 3, 2)
    >>> tuple(sorted_outcomes[i] for i in which)
    (1000, 10, 1000, 100)
    >>> r_select = r_values.select_iterable(which) ; r_select
    SelectionRoller(
      which=(3, 1, 3, 2),
      sources=(
        PoolRoller(
          sources=(
            ValueRoller(value=10000, annotation=''),
            ValueRoller(value=1, annotation=''),
            ValueRoller(value=1000, annotation=''),
            ValueRoller(value=10, annotation=''),
            ValueRoller(value=100, annotation=''),
          ),
          annotation='',
        ),
      ),
      annotation='',
    )
    >>> roll = r_select.roll()
    >>> tuple(roll.outcomes())
    (1000, 10, 1000, 100)
    >>> roll
    Roll(
      r=...,
      roll_outcomes=(
        RollOutcome(
          value=1000,
          sources=(),
        ),
        RollOutcome(
          value=10,
          sources=(),
        ),
        RollOutcome(
          value=1000,
          sources=(),
        ),
        RollOutcome(
          value=100,
          sources=(),
        ),
        RollOutcome(
          value=None,
          sources=(
            RollOutcome(
              value=1,
              sources=(),
            ),
          ),
        ),
        RollOutcome(
          value=None,
          sources=(
            RollOutcome(
              value=10000,
              sources=(),
            ),
          ),
        ),
      ),
      source_rolls=...,
    )

    ```
    """
    __slots__: Any = ("_which",)

    # ---- Initializer -----------------------------------------------------------------

    @beartype
    def __init__(
        self,
        which: Iterable[_GetItemT],
        sources: Iterable[_SourceT],
        annotation: Any = "",
        **kw,
    ):
        r"Initializer."
        super().__init__(sources=sources, annotation=annotation, **kw)
        self._which = tuple(which)

    # ---- Overrides -------------------------------------------------------------------

    @beartype
    def __repr__(self) -> str:
        return f"""{type(self).__name__}(
  which={self.which!r},
  sources=({_seq_repr(self.sources)}),
  annotation={self.annotation!r},
)"""

    @beartype
    def __eq__(self, other) -> bool:
        return super().__eq__(other) and self.which == other.which

    @beartype
    def roll(self) -> "Roll":
        r""""""
        source_rolls = list(self.source_rolls())
        roll_outcomes = list(
            roll_outcome
            for roll_outcome in chain.from_iterable(source_rolls)
            if roll_outcome.value is not None
        )
        roll_outcomes.sort(key=attrgetter("value"))
        all_indexes = tuple(range(len(roll_outcomes)))
        selected_indexes = tuple(getitems(all_indexes, self.which))

        def _selected_roll_outcomes():
            for selected_index in selected_indexes:
                selected_roll_outcome = roll_outcomes[selected_index]
                assert selected_roll_outcome.value is not None
                yield selected_roll_outcome

            for excluded_index in set(all_indexes) - set(selected_indexes):
                yield roll_outcomes[excluded_index].euthanize()

        return Roll(
            self,
            roll_outcomes=_selected_roll_outcomes(),
            source_rolls=source_rolls,
        )

    # ---- Properties ------------------------------------------------------------------

    @property
    def which(self) -> tuple[_GetItemT, ...]:
        r"""
        The selector this roller applies to the sorted outcomes of its sole source.
        """
        return self._which

__slots__: Any = ('_which') class-attribute instance-attribute

which: tuple[_GetItemT, ...] property

The selector this roller applies to the sorted outcomes of its sole source.

__eq__(other) -> bool

Source code in dyce/r.py
1910
1911
1912
@beartype
def __eq__(self, other) -> bool:
    return super().__eq__(other) and self.which == other.which

__init__(which: Iterable[_GetItemT], sources: Iterable[_SourceT], annotation: Any = '', **kw: Any)

Initializer.

Source code in dyce/r.py
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
@beartype
def __init__(
    self,
    which: Iterable[_GetItemT],
    sources: Iterable[_SourceT],
    annotation: Any = "",
    **kw,
):
    r"Initializer."
    super().__init__(sources=sources, annotation=annotation, **kw)
    self._which = tuple(which)

__repr__() -> str

Source code in dyce/r.py
1902
1903
1904
1905
1906
1907
1908
    @beartype
    def __repr__(self) -> str:
        return f"""{type(self).__name__}(
  which={self.which!r},
  sources=({_seq_repr(self.sources)}),
  annotation={self.annotation!r},
)"""

roll() -> Roll

Source code in dyce/r.py
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
@beartype
def roll(self) -> "Roll":
    r""""""
    source_rolls = list(self.source_rolls())
    roll_outcomes = list(
        roll_outcome
        for roll_outcome in chain.from_iterable(source_rolls)
        if roll_outcome.value is not None
    )
    roll_outcomes.sort(key=attrgetter("value"))
    all_indexes = tuple(range(len(roll_outcomes)))
    selected_indexes = tuple(getitems(all_indexes, self.which))

    def _selected_roll_outcomes():
        for selected_index in selected_indexes:
            selected_roll_outcome = roll_outcomes[selected_index]
            assert selected_roll_outcome.value is not None
            yield selected_roll_outcome

        for excluded_index in set(all_indexes) - set(selected_indexes):
            yield roll_outcomes[excluded_index].euthanize()

    return Roll(
        self,
        roll_outcomes=_selected_roll_outcomes(),
        source_rolls=source_rolls,
    )

Roll

Bases: Sequence[RollOutcome]

Experimental

This class should be considered experimental and may change or disappear in future versions.

An immutable roll result (or “roll” for short). More specifically, the result of calling the R.roll method. Rolls are sequences of RollOutcome objects that can be assembled into trees.

Source code in dyce/r.py
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
class Roll(Sequence[RollOutcome]):
    r"""
    !!! warning "Experimental"

        This class should be considered experimental and may change or disappear in
        future versions.

    An immutable roll result (or “roll” for short). More specifically, the result of
    calling the [``R.roll`` method][dyce.r.R.roll]. Rolls are sequences of
    [``RollOutcome`` objects][dyce.r.RollOutcome] that can be assembled into trees.
    """
    __slots__: Any = ("_r", "_roll_outcomes", "_source_rolls")

    # ---- Initializer -----------------------------------------------------------------

    @experimental
    @beartype
    def __init__(
        self,
        r: R,
        roll_outcomes: Iterable[RollOutcome],
        source_rolls: Iterable["Roll"] = (),
    ):
        r"""
        Initializer.

        This initializer will associate each of *roll_outcomes* with the newly
        constructed roll if they do not already have a
        [``source_roll``][dyce.r.RollOutcome.source_roll].

        ``` python
        >>> r_4 = ValueRoller(4)
        >>> roll = r_4.roll()
        >>> new_roll = Roll(r_4, roll) ; new_roll
        Roll(
          r=ValueRoller(value=4, annotation=''),
          roll_outcomes=(
            RollOutcome(
              value=4,
              sources=(),
            ),
          ),
          source_rolls=(),
        )
        >>> roll[0].source_roll == roll
        True
        >>> roll[0].r == r_4
        True

        ```

        !!! note

            Technically, this violates the immutability of roll outcomes.

            ``dyce`` does not generally contemplate creation of rolls or roll outcomes
            outside the womb of [``R.roll``][dyce.r.R.roll] implementations.
            [``Roll`` objects][dyce.r.Roll] and
            [``RollOutcome`` objects][dyce.r.RollOutcome] generally mate for life, being
            created exclusively for (and in close proximity to) one another. A roll
            manipulating a roll outcome’s internal state post initialization may seem
            unseemly, but that intimacy is a fundamental part of their primordial
            ritual.

            That being said, you’re an adult. Do what you want. Just know that if you’re
            going to create your own roll outcomes and pimp them out all over town, they
            might pick something up along the way.

            See also the
            [``RollOutcome.source_roll`` property][dyce.r.RollOutcome.source_roll].
        """
        super().__init__()
        self._r = r
        self._roll_outcomes = tuple(roll_outcomes)
        self._source_rolls = tuple(source_rolls)

        for roll_outcome in self._roll_outcomes:
            if roll_outcome._roll is None:
                roll_outcome._roll = self

    # ---- Overrides -------------------------------------------------------------------

    @beartype
    def __repr__(self) -> str:
        return f"""{type(self).__name__}(
  r={indent(repr(self.r), "  ").strip()},
  roll_outcomes=({_seq_repr(self)}),
  source_rolls=({_seq_repr(self.source_rolls)}),
)"""

    @beartype
    def __len__(self) -> int:
        return len(self._roll_outcomes)

    @overload
    def __getitem__(self, key: SupportsIndex) -> RollOutcome:
        ...

    @overload
    def __getitem__(self, key: slice) -> tuple[RollOutcome, ...]:
        ...

    @beartype
    def __getitem__(
        self,
        key: _GetItemT,
    ) -> Union[RollOutcome, tuple[RollOutcome, ...]]:
        if isinstance(key, slice):
            return self._roll_outcomes[key]
        else:
            return self._roll_outcomes[__index__(key)]

    @beartype
    def __iter__(self) -> Iterator[RollOutcome]:
        return iter(self._roll_outcomes)

    # ---- Properties ------------------------------------------------------------------

    @property
    def annotation(self) -> Any:
        r"""
        Shorthand for ``#!python self.r.annotation``.

        See the [``R.annotation`` property][dyce.r.R.annotation].
        """
        return self.r.annotation

    @property
    def r(self) -> R:
        r"""
        The roller that generated the roll.
        """
        return self._r

    @property
    def source_rolls(self) -> tuple["Roll", ...]:
        r"""
        The source rolls from which this roll was generated.
        """
        return self._source_rolls

    # ---- Methods ---------------------------------------------------------------------

    @beartype
    def adopt(
        self,
        sources: Iterable["RollOutcome"] = (),
        coalesce_mode: CoalesceMode = CoalesceMode.REPLACE,
    ) -> "Roll":
        r"""
        Shorthand for ``#!python Roll(self.r, (roll_outcome.adopt(sources,
        coalesce_mode) for roll_outcome in self), self.source_rolls)``.
        """
        return type(self)(
            self.r,
            (roll_outcome.adopt(sources, coalesce_mode) for roll_outcome in self),
            self.source_rolls,
        )

    @beartype
    def outcomes(self) -> Iterator[RealLike]:
        r"""
        Shorthand for ``#!python (roll_outcome.value for roll_outcome in self if
        roll_outcome.value is not None)``.

        <!-- BEGIN MONKEY PATCH --
        For deterministic outcomes.

        >>> import random
        >>> from dyce import rng
        >>> rng.RNG = random.Random(1633056410)

          -- END MONKEY PATCH -->

        !!! info

            Unlike [``H.roll``][dyce.h.H.roll] and [``P.roll``][dyce.p.P.roll], these
            outcomes are *not* sorted. Instead, they retain the ordering as passed to
            [``__init__``][dyce.r.Roll.__init__].

            ``` python
            >>> r_3d6 = 3@R.from_value(H(6))
            >>> r_3d6_neg = 3@-R.from_value(H(6))
            >>> roll = R.from_sources(r_3d6, r_3d6_neg).roll()
            >>> tuple(roll.outcomes())
            (1, 3, 1, -4, -6, -1)
            >>> len(roll)
            6

            ```
        """
        return (
            roll_outcome.value
            for roll_outcome in self
            if roll_outcome.value is not None
        )

    @beartype
    def total(self) -> RealLike:
        r"""
        Shorthand for ``#!python sum(self.outcomes())``.
        """
        return sum(self.outcomes())

__slots__: Any = ('_r', '_roll_outcomes', '_source_rolls') class-attribute instance-attribute

annotation: Any property

Shorthand for self.r.annotation.

See the R.annotation property.

r: R property

The roller that generated the roll.

source_rolls: tuple[Roll, ...] property

The source rolls from which this roll was generated.

__getitem__(key: _GetItemT) -> Union[RollOutcome, tuple[RollOutcome, ...]]

Source code in dyce/r.py
2840
2841
2842
2843
2844
2845
2846
2847
2848
@beartype
def __getitem__(
    self,
    key: _GetItemT,
) -> Union[RollOutcome, tuple[RollOutcome, ...]]:
    if isinstance(key, slice):
        return self._roll_outcomes[key]
    else:
        return self._roll_outcomes[__index__(key)]

__init__(r: R, roll_outcomes: Iterable[RollOutcome], source_rolls: Iterable[Roll] = ())

Initializer.

This initializer will associate each of roll_outcomes with the newly constructed roll if they do not already have a source_roll.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
>>> r_4 = ValueRoller(4)
>>> roll = r_4.roll()
>>> new_roll = Roll(r_4, roll) ; new_roll
Roll(
  r=ValueRoller(value=4, annotation=''),
  roll_outcomes=(
    RollOutcome(
      value=4,
      sources=(),
    ),
  ),
  source_rolls=(),
)
>>> roll[0].source_roll == roll
True
>>> roll[0].r == r_4
True

Note

Technically, this violates the immutability of roll outcomes.

dyce does not generally contemplate creation of rolls or roll outcomes outside the womb of R.roll implementations. Roll objects and RollOutcome objects generally mate for life, being created exclusively for (and in close proximity to) one another. A roll manipulating a roll outcome’s internal state post initialization may seem unseemly, but that intimacy is a fundamental part of their primordial ritual.

That being said, you’re an adult. Do what you want. Just know that if you’re going to create your own roll outcomes and pimp them out all over town, they might pick something up along the way.

See also the RollOutcome.source_roll property.

Source code in dyce/r.py
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
@experimental
@beartype
def __init__(
    self,
    r: R,
    roll_outcomes: Iterable[RollOutcome],
    source_rolls: Iterable["Roll"] = (),
):
    r"""
    Initializer.

    This initializer will associate each of *roll_outcomes* with the newly
    constructed roll if they do not already have a
    [``source_roll``][dyce.r.RollOutcome.source_roll].

    ``` python
    >>> r_4 = ValueRoller(4)
    >>> roll = r_4.roll()
    >>> new_roll = Roll(r_4, roll) ; new_roll
    Roll(
      r=ValueRoller(value=4, annotation=''),
      roll_outcomes=(
        RollOutcome(
          value=4,
          sources=(),
        ),
      ),
      source_rolls=(),
    )
    >>> roll[0].source_roll == roll
    True
    >>> roll[0].r == r_4
    True

    ```

    !!! note

        Technically, this violates the immutability of roll outcomes.

        ``dyce`` does not generally contemplate creation of rolls or roll outcomes
        outside the womb of [``R.roll``][dyce.r.R.roll] implementations.
        [``Roll`` objects][dyce.r.Roll] and
        [``RollOutcome`` objects][dyce.r.RollOutcome] generally mate for life, being
        created exclusively for (and in close proximity to) one another. A roll
        manipulating a roll outcome’s internal state post initialization may seem
        unseemly, but that intimacy is a fundamental part of their primordial
        ritual.

        That being said, you’re an adult. Do what you want. Just know that if you’re
        going to create your own roll outcomes and pimp them out all over town, they
        might pick something up along the way.

        See also the
        [``RollOutcome.source_roll`` property][dyce.r.RollOutcome.source_roll].
    """
    super().__init__()
    self._r = r
    self._roll_outcomes = tuple(roll_outcomes)
    self._source_rolls = tuple(source_rolls)

    for roll_outcome in self._roll_outcomes:
        if roll_outcome._roll is None:
            roll_outcome._roll = self

__iter__() -> Iterator[RollOutcome]

Source code in dyce/r.py
2850
2851
2852
@beartype
def __iter__(self) -> Iterator[RollOutcome]:
    return iter(self._roll_outcomes)

__len__() -> int

Source code in dyce/r.py
2828
2829
2830
@beartype
def __len__(self) -> int:
    return len(self._roll_outcomes)

__repr__() -> str

Source code in dyce/r.py
2820
2821
2822
2823
2824
2825
2826
    @beartype
    def __repr__(self) -> str:
        return f"""{type(self).__name__}(
  r={indent(repr(self.r), "  ").strip()},
  roll_outcomes=({_seq_repr(self)}),
  source_rolls=({_seq_repr(self.source_rolls)}),
)"""

adopt(sources: Iterable[RollOutcome] = (), coalesce_mode: CoalesceMode = CoalesceMode.REPLACE) -> Roll

Shorthand for Roll(self.r, (roll_outcome.adopt(sources,coalesce_mode) for roll_outcome in self), self.source_rolls).

Source code in dyce/r.py
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
@beartype
def adopt(
    self,
    sources: Iterable["RollOutcome"] = (),
    coalesce_mode: CoalesceMode = CoalesceMode.REPLACE,
) -> "Roll":
    r"""
    Shorthand for ``#!python Roll(self.r, (roll_outcome.adopt(sources,
    coalesce_mode) for roll_outcome in self), self.source_rolls)``.
    """
    return type(self)(
        self.r,
        (roll_outcome.adopt(sources, coalesce_mode) for roll_outcome in self),
        self.source_rolls,
    )

outcomes() -> Iterator[RealLike]

Shorthand for (roll_outcome.value for roll_outcome in self ifroll_outcome.value is not None).

Info

Unlike H.roll and P.roll, these outcomes are not sorted. Instead, they retain the ordering as passed to __init__.

1
2
3
4
5
6
7
>>> r_3d6 = 3@R.from_value(H(6))
>>> r_3d6_neg = 3@-R.from_value(H(6))
>>> roll = R.from_sources(r_3d6, r_3d6_neg).roll()
>>> tuple(roll.outcomes())
(1, 3, 1, -4, -6, -1)
>>> len(roll)
6
Source code in dyce/r.py
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
@beartype
def outcomes(self) -> Iterator[RealLike]:
    r"""
    Shorthand for ``#!python (roll_outcome.value for roll_outcome in self if
    roll_outcome.value is not None)``.

    <!-- BEGIN MONKEY PATCH --
    For deterministic outcomes.

    >>> import random
    >>> from dyce import rng
    >>> rng.RNG = random.Random(1633056410)

      -- END MONKEY PATCH -->

    !!! info

        Unlike [``H.roll``][dyce.h.H.roll] and [``P.roll``][dyce.p.P.roll], these
        outcomes are *not* sorted. Instead, they retain the ordering as passed to
        [``__init__``][dyce.r.Roll.__init__].

        ``` python
        >>> r_3d6 = 3@R.from_value(H(6))
        >>> r_3d6_neg = 3@-R.from_value(H(6))
        >>> roll = R.from_sources(r_3d6, r_3d6_neg).roll()
        >>> tuple(roll.outcomes())
        (1, 3, 1, -4, -6, -1)
        >>> len(roll)
        6

        ```
    """
    return (
        roll_outcome.value
        for roll_outcome in self
        if roll_outcome.value is not None
    )

total() -> RealLike

Shorthand for sum(self.outcomes()).

Source code in dyce/r.py
2935
2936
2937
2938
2939
2940
@beartype
def total(self) -> RealLike:
    r"""
    Shorthand for ``#!python sum(self.outcomes())``.
    """
    return sum(self.outcomes())

RollOutcome

Experimental

This class should be considered experimental and may change or disappear in future versions.

A single, (mostly) immutable outcome generated by a roll.

Source code in dyce/r.py
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
class RollOutcome:
    r"""
    !!! warning "Experimental"

        This class should be considered experimental and may change or disappear in
        future versions.

    A single, ([mostly][dyce.r.Roll.__init__]) immutable outcome generated by a roll.
    """
    __slots__: Any = ("_roll", "_sources", "_value")

    # ---- Initializer -----------------------------------------------------------------

    @experimental
    @beartype
    def __init__(
        self,
        value: Optional[RealLike],
        # TODO(posita): See <https://github.com/beartype/beartype/issues/152>
        sources: Iterable["RollOutcome"] = (),
    ):
        r"Initializer."
        super().__init__()
        self._value = value
        self._sources = tuple(sources)
        self._roll: Optional[Roll] = None

        if self._value is None and not self._sources:
            raise ValueError("value can only be None if sources is non-empty")

    # ---- Overrides -------------------------------------------------------------------

    @beartype
    def __repr__(self) -> str:
        return f"""{type(self).__name__}(
  value={repr(self.value)},
  sources=({_seq_repr(self.sources)}),
)"""

    @beartype
    # TODO(posita): See <https://github.com/python/mypy/issues/10943>
    def __lt__(self, other: _RollOutcomeOperandT) -> bool:  # type: ignore [has-type]
        if (
            isinstance(other, RollOutcome)
            and self.value is not None
            and other.value is not None
        ):
            return bool(__lt__(self.value, other.value))
        else:
            return NotImplemented

    @beartype
    # TODO(posita): See <https://github.com/python/mypy/issues/10943>
    def __le__(self, other: _RollOutcomeOperandT) -> bool:  # type: ignore [has-type]
        if (
            isinstance(other, RollOutcome)
            and self.value is not None
            and other.value is not None
        ):
            return bool(__le__(self.value, other.value))
        else:
            return NotImplemented

    @beartype
    def __eq__(self, other) -> bool:
        if isinstance(other, RollOutcome):
            return bool(__eq__(self.value, other.value))
        else:
            return super().__eq__(other)

    @beartype
    def __ne__(self, other) -> bool:
        if isinstance(other, RollOutcome):
            return bool(__ne__(self.value, other.value))
        else:
            return super().__ne__(other)

    @beartype
    def __gt__(self, other: _RollOutcomeOperandT) -> bool:
        if (
            isinstance(other, RollOutcome)
            and self.value is not None
            and other.value is not None
        ):
            return bool(__gt__(self.value, other.value))
        else:
            return NotImplemented

    @beartype
    def __ge__(self, other: _RollOutcomeOperandT) -> bool:
        if (
            isinstance(other, RollOutcome)
            and self.value is not None
            and other.value is not None
        ):
            return bool(__ge__(self.value, other.value))
        else:
            return NotImplemented

    @beartype
    def __add__(self, other: _RollOutcomeOperandT) -> "RollOutcome":
        try:
            return self.map(__add__, other)
        except NotImplementedError:
            return NotImplemented

    @beartype
    def __radd__(self, other: RealLike) -> "RollOutcome":
        try:
            return self.rmap(other, __add__)
        except NotImplementedError:
            return NotImplemented

    @beartype
    def __sub__(self, other: _RollOutcomeOperandT) -> "RollOutcome":
        try:
            return self.map(__sub__, other)
        except NotImplementedError:
            return NotImplemented

    @beartype
    def __rsub__(self, other: RealLike) -> "RollOutcome":
        try:
            return self.rmap(other, __sub__)
        except NotImplementedError:
            return NotImplemented

    @beartype
    def __mul__(self, other: _RollOutcomeOperandT) -> "RollOutcome":
        try:
            return self.map(__mul__, other)
        except NotImplementedError:
            return NotImplemented

    @beartype
    def __rmul__(self, other: RealLike) -> "RollOutcome":
        try:
            return self.rmap(other, __mul__)
        except NotImplementedError:
            return NotImplemented

    @beartype
    def __truediv__(self, other: _RollOutcomeOperandT) -> "RollOutcome":
        try:
            return self.map(__truediv__, other)
        except NotImplementedError:
            return NotImplemented

    @beartype
    def __rtruediv__(self, other: RealLike) -> "RollOutcome":
        try:
            return self.rmap(other, __truediv__)
        except NotImplementedError:
            return NotImplemented

    @beartype
    def __floordiv__(self, other: _RollOutcomeOperandT) -> "RollOutcome":
        try:
            return self.map(__floordiv__, other)
        except NotImplementedError:
            return NotImplemented

    @beartype
    def __rfloordiv__(self, other: RealLike) -> "RollOutcome":
        try:
            return self.rmap(other, __floordiv__)
        except NotImplementedError:
            return NotImplemented

    @beartype
    def __mod__(self, other: _RollOutcomeOperandT) -> "RollOutcome":
        try:
            return self.map(__mod__, other)
        except NotImplementedError:
            return NotImplemented

    @beartype
    def __rmod__(self, other: RealLike) -> "RollOutcome":
        try:
            return self.rmap(other, __mod__)
        except NotImplementedError:
            return NotImplemented

    @beartype
    def __pow__(self, other: _RollOutcomeOperandT) -> "RollOutcome":
        try:
            return self.map(__pow__, other)
        except NotImplementedError:
            return NotImplemented

    @beartype
    def __rpow__(self, other: RealLike) -> "RollOutcome":
        try:
            return self.rmap(other, __pow__)
        except NotImplementedError:
            return NotImplemented

    @beartype
    # TODO(posita): See <https://github.com/beartype/beartype/issues/152>
    def __and__(self, other: Union["RollOutcome", SupportsInt]) -> "RollOutcome":
        try:
            if isinstance(other, SupportsInt):
                other = as_int(other)

            return self.map(__and__, other)
        except (NotImplementedError, TypeError):
            return NotImplemented

    @beartype
    def __rand__(self, other: SupportsInt) -> "RollOutcome":
        try:
            return self.rmap(as_int(other), __and__)
        except (NotImplementedError, TypeError):
            return NotImplemented

    @beartype
    # TODO(posita): See <https://github.com/beartype/beartype/issues/152>
    def __xor__(self, other: Union["RollOutcome", SupportsInt]) -> "RollOutcome":
        try:
            if isinstance(other, SupportsInt):
                other = as_int(other)

            return self.map(__xor__, other)
        except (NotImplementedError, TypeError):
            return NotImplemented

    @beartype
    def __rxor__(self, other: SupportsInt) -> "RollOutcome":
        try:
            return self.rmap(as_int(other), __xor__)
        except (NotImplementedError, TypeError):
            return NotImplemented

    @beartype
    # TODO(posita): See <https://github.com/beartype/beartype/issues/152>
    def __or__(self, other: Union["RollOutcome", SupportsInt]) -> "RollOutcome":
        try:
            if isinstance(other, SupportsInt):
                other = as_int(other)

            return self.map(__or__, other)
        except (NotImplementedError, TypeError):
            return NotImplemented

    @beartype
    def __ror__(self, other: SupportsInt) -> "RollOutcome":
        try:
            return self.rmap(as_int(other), __or__)
        except (NotImplementedError, TypeError):
            return NotImplemented

    @beartype
    def __neg__(self) -> "RollOutcome":
        return self.umap(__neg__)

    @beartype
    def __pos__(self) -> "RollOutcome":
        return self.umap(__pos__)

    @beartype
    def __abs__(self) -> "RollOutcome":
        return self.umap(__abs__)

    @beartype
    def __invert__(self) -> "RollOutcome":
        return self.umap(__invert__)

    # ---- Properties ------------------------------------------------------------------

    @property
    def annotation(self) -> Any:
        r"""
        Shorthand for ``#!python self.source_roll.annotation``.

        See the [``source_roll``][dyce.r.RollOutcome.source_roll] and
        [``Roll.annotation``][dyce.r.Roll.annotation] properties.
        """
        return self.source_roll.annotation

    @property
    def r(self) -> R:
        r"""
        Shorthand for ``#!python self.source_roll.r``.

        See the [``source_roll``][dyce.r.RollOutcome.source_roll] and
        [``Roll.r``][dyce.r.Roll.r] properties.
        """
        return self.source_roll.r

    @property
    def source_roll(self) -> "Roll":
        r"""
        Returns the roll if one has been associated with this roll outcome. Usually that
        happens by submitting the roll outcome to the
        [``Roll.__init__`` method][dyce.r.Roll.__init__] inside a
        [``R.roll`` method][dyce.r.R.roll] implementation. Accessing this property
        before the roll outcome has been associated with a roll is considered a
        programming error.

        ``` python
        >>> ro = RollOutcome(4)
        >>> ro.source_roll
        Traceback (most recent call last):
          ...
        AssertionError: RollOutcome.source_roll accessed before associating the roll outcome with a roll (usually via Roll.__init__)
        assert None is not None
        >>> roll = Roll(R.from_value(4), roll_outcomes=(ro,))
        >>> ro.source_roll
        Roll(
          r=ValueRoller(value=4, annotation=''),
          roll_outcomes=(
            RollOutcome(
              value=4,
              sources=(),
            ),
          ),
          source_rolls=(),
        )

        ```
        """
        assert (
            self._roll is not None
        ), "RollOutcome.source_roll accessed before associating the roll outcome with a roll (usually via Roll.__init__)"

        return self._roll

    @property
    def sources(self) -> tuple["RollOutcome", ...]:
        r"""
        The source roll outcomes from which this roll outcome was generated.
        """
        return self._sources

    @property
    def value(self) -> Optional[RealLike]:
        r"""
        The outcome value. A value of ``#!python None`` is used to signal that a source’s
        roll outcome was excluded by the roller.
        """
        return self._value

    # ---- Methods ---------------------------------------------------------------------

    @beartype
    def map(
        self,
        bin_op: _BinaryOperatorT,
        right_operand: _RollOutcomeOperandT,
    ) -> "RollOutcome":
        r"""
        Applies *bin_op* to the value of this roll outcome as the left operand and
        *right_operand* as the right. Shorthands exist for many arithmetic operators and
        comparators.

        ``` python
        >>> import operator
        >>> two = RollOutcome(2)
        >>> two.map(operator.__pow__, 10)
        RollOutcome(
          value=1024,
          sources=(
            RollOutcome(
              value=2,
              sources=(),
            ),
          ),
        )
        >>> two.map(operator.__pow__, 10) == two ** 10
        True

        ```
        """
        if isinstance(right_operand, RollOutcome):
            sources: tuple[RollOutcome, ...] = (self, right_operand)
            right_operand_value: Optional[RealLike] = right_operand.value
        else:
            sources = (self,)
            right_operand_value = right_operand

        if isinstance(right_operand_value, RealLike):
            return type(self)(bin_op(self.value, right_operand_value), sources)
        else:
            raise NotImplementedError

    @beartype
    def rmap(self, left_operand: RealLike, bin_op: _BinaryOperatorT) -> "RollOutcome":
        r"""
        Analogous to the [``map`` method][dyce.r.RollOutcome.map], but where the caller
        supplies *left_operand*.

        ``` python
        >>> import operator
        >>> two = RollOutcome(2)
        >>> two.rmap(10, operator.__pow__)
        RollOutcome(
          value=100,
          sources=(
            RollOutcome(
              value=2,
              sources=(),
            ),
          ),
        )
        >>> two.rmap(10, operator.__pow__) == 10 ** two
        True

        ```

        !!! note

            The positions of *left_operand* and *bin_op* are different from
            [``map`` method][dyce.r.RollOutcome.map]. This is intentional and serves as
            a reminder of operand ordering.
        """
        if isinstance(left_operand, RealLike):
            return type(self)(bin_op(left_operand, self.value), sources=(self,))
        else:
            raise NotImplementedError

    @beartype
    def umap(
        self,
        un_op: _UnaryOperatorT,
    ) -> "RollOutcome":
        r"""
        Applies *un_op* to the value of this roll outcome. Shorthands exist for many
        arithmetic operators and comparators.

        ``` python
        >>> import operator
        >>> two_neg = RollOutcome(-2)
        >>> two_neg.umap(operator.__neg__)
        RollOutcome(
          value=2,
          sources=(
            RollOutcome(
              value=-2,
              sources=(),
            ),
          ),
        )
        >>> two_neg.umap(operator.__neg__) == -two_neg
        True

        ```
        """
        return type(self)(un_op(self.value), sources=(self,))

    @beartype
    def lt(self, other: _RollOutcomeOperandT) -> "RollOutcome":
        if isinstance(other, RollOutcome):
            return type(self)(bool(__lt__(self, other)), sources=(self, other))
        elif self.value is not None:
            return type(self)(bool(__lt__(self.value, other)), sources=(self,))
        else:
            raise ValueError(f"unable to compare {self} to {other}")

    @beartype
    def le(self, other: _RollOutcomeOperandT) -> "RollOutcome":
        if isinstance(other, RollOutcome):
            return type(self)(bool(__le__(self, other)), sources=(self, other))
        elif self.value is not None:
            return type(self)(bool(__le__(self.value, other)), sources=(self,))
        else:
            raise ValueError(f"unable to compare {self} to {other}")

    @beartype
    def eq(self, other: _RollOutcomeOperandT) -> "RollOutcome":
        if isinstance(other, RollOutcome):
            return type(self)(bool(__eq__(self, other)), sources=(self, other))
        elif self.value is not None:
            return type(self)(bool(__eq__(self.value, other)), sources=(self,))
        else:
            raise ValueError(f"unable to compare {self} to {other}")

    @beartype
    def ne(self, other: _RollOutcomeOperandT) -> "RollOutcome":
        if isinstance(other, RollOutcome):
            return type(self)(bool(__ne__(self, other)), sources=(self, other))
        else:
            return type(self)(bool(__ne__(self.value, other)), sources=(self,))

    @beartype
    def gt(self, other: _RollOutcomeOperandT) -> "RollOutcome":
        if isinstance(other, RollOutcome):
            return type(self)(bool(__gt__(self, other)), sources=(self, other))
        elif self.value is not None:
            return type(self)(bool(__gt__(self.value, other)), sources=(self,))
        else:
            raise ValueError(f"unable to compare {self} to {other}")

    @beartype
    def ge(self, other: _RollOutcomeOperandT) -> "RollOutcome":
        if isinstance(other, RollOutcome):
            return type(self)(bool(__ge__(self, other)), sources=(self, other))
        elif self.value is not None:
            return type(self)(bool(__ge__(self.value, other)), sources=(self,))
        else:
            raise ValueError(f"unable to compare {self} to {other}")

    @beartype
    def is_even(self) -> "RollOutcome":
        r"""
        Shorthand for: ``#!python self.umap(dyce.types.is_even)``.

        See the [``umap`` method][dyce.r.RollOutcome.umap].
        """
        return self.umap(is_even)

    @beartype
    def is_odd(self) -> "RollOutcome":
        r"""
        Shorthand for: ``#!python self.umap(dyce.types.is_even)``.

        See the [``umap`` method][dyce.r.RollOutcome.umap].
        """
        return self.umap(is_odd)

    @beartype
    def adopt(
        self,
        sources: Iterable["RollOutcome"] = (),
        coalesce_mode: CoalesceMode = CoalesceMode.REPLACE,
    ) -> "RollOutcome":
        r"""
        Creates and returns a new roll outcome identical to this roll outcome, but with
        *sources* replacing or appended to this roll outcome’s sources in accordance
        with *coalesce_mode*.

        ``` python
        >>> from dyce.r import CoalesceMode
        >>> orig = RollOutcome(1, sources=(RollOutcome(2),)) ; orig
        RollOutcome(
          value=1,
          sources=(
            RollOutcome(
              value=2,
              sources=(),
            ),
          ),
        )
        >>> orig.adopt((RollOutcome(3),), coalesce_mode=CoalesceMode.REPLACE)
        RollOutcome(
          value=1,
          sources=(
            RollOutcome(
              value=3,
              sources=(),
            ),
          ),
        )
        >>> orig.adopt((RollOutcome(3),), coalesce_mode=CoalesceMode.APPEND)
        RollOutcome(
          value=1,
          sources=(
            RollOutcome(
              value=2,
              sources=(),
            ),
            RollOutcome(
              value=3,
              sources=(),
            ),
          ),
        )

        ```
        """
        if coalesce_mode is CoalesceMode.REPLACE:
            adopted_sources = sources
        elif coalesce_mode is CoalesceMode.APPEND:
            adopted_sources = chain(self.sources, sources)
        else:
            assert False, f"unrecognized substitution mode {self.coalesce_mode!r}"

        adopted_roll_outcome = type(self)(self.value, adopted_sources)
        adopted_roll_outcome._roll = self._roll

        return adopted_roll_outcome

    @beartype
    def euthanize(self) -> "RollOutcome":
        r"""
        Shorthand for ``#!python self.umap(lambda operand: None)``.

        ``` python
        >>> two = RollOutcome(2)
        >>> two.euthanize()
        RollOutcome(
          value=None,
          sources=(
            RollOutcome(
              value=2,
              sources=(),
            ),
          ),
        )

        ```

        See the [``umap`` method][dyce.r.RollOutcome.umap].
        """

        def _euthanize(operand: Optional[RealLike]) -> None:
            pass

        return self.umap(_euthanize)

__slots__: Any = ('_roll', '_sources', '_value') class-attribute instance-attribute

annotation: Any property

Shorthand for self.source_roll.annotation.

See the source_roll and Roll.annotation properties.

r: R property

Shorthand for self.source_roll.r.

See the source_roll and Roll.r properties.

source_roll: Roll property

Returns the roll if one has been associated with this roll outcome. Usually that happens by submitting the roll outcome to the Roll.__init__ method inside a R.roll method implementation. Accessing this property before the roll outcome has been associated with a roll is considered a programming error.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
>>> ro = RollOutcome(4)
>>> ro.source_roll
Traceback (most recent call last):
  ...
AssertionError: RollOutcome.source_roll accessed before associating the roll outcome with a roll (usually via Roll.__init__)
assert None is not None
>>> roll = Roll(R.from_value(4), roll_outcomes=(ro,))
>>> ro.source_roll
Roll(
  r=ValueRoller(value=4, annotation=''),
  roll_outcomes=(
    RollOutcome(
      value=4,
      sources=(),
    ),
  ),
  source_rolls=(),
)

sources: tuple[RollOutcome, ...] property

The source roll outcomes from which this roll outcome was generated.

value: Optional[RealLike] property

The outcome value. A value of None is used to signal that a source’s roll outcome was excluded by the roller.

__abs__() -> RollOutcome

Source code in dyce/r.py
2387
2388
2389
@beartype
def __abs__(self) -> "RollOutcome":
    return self.umap(__abs__)

__add__(other: _RollOutcomeOperandT) -> RollOutcome

Source code in dyce/r.py
2227
2228
2229
2230
2231
2232
@beartype
def __add__(self, other: _RollOutcomeOperandT) -> "RollOutcome":
    try:
        return self.map(__add__, other)
    except NotImplementedError:
        return NotImplemented

__and__(other: Union[RollOutcome, SupportsInt]) -> RollOutcome

Source code in dyce/r.py
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
@beartype
# TODO(posita): See <https://github.com/beartype/beartype/issues/152>
def __and__(self, other: Union["RollOutcome", SupportsInt]) -> "RollOutcome":
    try:
        if isinstance(other, SupportsInt):
            other = as_int(other)

        return self.map(__and__, other)
    except (NotImplementedError, TypeError):
        return NotImplemented

__eq__(other) -> bool

Source code in dyce/r.py
2191
2192
2193
2194
2195
2196
@beartype
def __eq__(self, other) -> bool:
    if isinstance(other, RollOutcome):
        return bool(__eq__(self.value, other.value))
    else:
        return super().__eq__(other)

__floordiv__(other: _RollOutcomeOperandT) -> RollOutcome

Source code in dyce/r.py
2283
2284
2285
2286
2287
2288
@beartype
def __floordiv__(self, other: _RollOutcomeOperandT) -> "RollOutcome":
    try:
        return self.map(__floordiv__, other)
    except NotImplementedError:
        return NotImplemented

__ge__(other: _RollOutcomeOperandT) -> bool

Source code in dyce/r.py
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
@beartype
def __ge__(self, other: _RollOutcomeOperandT) -> bool:
    if (
        isinstance(other, RollOutcome)
        and self.value is not None
        and other.value is not None
    ):
        return bool(__ge__(self.value, other.value))
    else:
        return NotImplemented

__gt__(other: _RollOutcomeOperandT) -> bool

Source code in dyce/r.py
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
@beartype
def __gt__(self, other: _RollOutcomeOperandT) -> bool:
    if (
        isinstance(other, RollOutcome)
        and self.value is not None
        and other.value is not None
    ):
        return bool(__gt__(self.value, other.value))
    else:
        return NotImplemented

__init__(value: Optional[RealLike], sources: Iterable[RollOutcome] = ())

Initializer.

Source code in dyce/r.py
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
@experimental
@beartype
def __init__(
    self,
    value: Optional[RealLike],
    # TODO(posita): See <https://github.com/beartype/beartype/issues/152>
    sources: Iterable["RollOutcome"] = (),
):
    r"Initializer."
    super().__init__()
    self._value = value
    self._sources = tuple(sources)
    self._roll: Optional[Roll] = None

    if self._value is None and not self._sources:
        raise ValueError("value can only be None if sources is non-empty")

__invert__() -> RollOutcome

Source code in dyce/r.py
2391
2392
2393
@beartype
def __invert__(self) -> "RollOutcome":
    return self.umap(__invert__)

__le__(other: _RollOutcomeOperandT) -> bool

Source code in dyce/r.py
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
@beartype
# TODO(posita): See <https://github.com/python/mypy/issues/10943>
def __le__(self, other: _RollOutcomeOperandT) -> bool:  # type: ignore [has-type]
    if (
        isinstance(other, RollOutcome)
        and self.value is not None
        and other.value is not None
    ):
        return bool(__le__(self.value, other.value))
    else:
        return NotImplemented

__lt__(other: _RollOutcomeOperandT) -> bool

Source code in dyce/r.py
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
@beartype
# TODO(posita): See <https://github.com/python/mypy/issues/10943>
def __lt__(self, other: _RollOutcomeOperandT) -> bool:  # type: ignore [has-type]
    if (
        isinstance(other, RollOutcome)
        and self.value is not None
        and other.value is not None
    ):
        return bool(__lt__(self.value, other.value))
    else:
        return NotImplemented

__mod__(other: _RollOutcomeOperandT) -> RollOutcome

Source code in dyce/r.py
2297
2298
2299
2300
2301
2302
@beartype
def __mod__(self, other: _RollOutcomeOperandT) -> "RollOutcome":
    try:
        return self.map(__mod__, other)
    except NotImplementedError:
        return NotImplemented

__mul__(other: _RollOutcomeOperandT) -> RollOutcome

Source code in dyce/r.py
2255
2256
2257
2258
2259
2260
@beartype
def __mul__(self, other: _RollOutcomeOperandT) -> "RollOutcome":
    try:
        return self.map(__mul__, other)
    except NotImplementedError:
        return NotImplemented

__ne__(other) -> bool

Source code in dyce/r.py
2198
2199
2200
2201
2202
2203
@beartype
def __ne__(self, other) -> bool:
    if isinstance(other, RollOutcome):
        return bool(__ne__(self.value, other.value))
    else:
        return super().__ne__(other)

__neg__() -> RollOutcome

Source code in dyce/r.py
2379
2380
2381
@beartype
def __neg__(self) -> "RollOutcome":
    return self.umap(__neg__)

__or__(other: Union[RollOutcome, SupportsInt]) -> RollOutcome

Source code in dyce/r.py
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
@beartype
# TODO(posita): See <https://github.com/beartype/beartype/issues/152>
def __or__(self, other: Union["RollOutcome", SupportsInt]) -> "RollOutcome":
    try:
        if isinstance(other, SupportsInt):
            other = as_int(other)

        return self.map(__or__, other)
    except (NotImplementedError, TypeError):
        return NotImplemented

__pos__() -> RollOutcome

Source code in dyce/r.py
2383
2384
2385
@beartype
def __pos__(self) -> "RollOutcome":
    return self.umap(__pos__)

__pow__(other: _RollOutcomeOperandT) -> RollOutcome

Source code in dyce/r.py
2311
2312
2313
2314
2315
2316
@beartype
def __pow__(self, other: _RollOutcomeOperandT) -> "RollOutcome":
    try:
        return self.map(__pow__, other)
    except NotImplementedError:
        return NotImplemented

__radd__(other: RealLike) -> RollOutcome

Source code in dyce/r.py
2234
2235
2236
2237
2238
2239
@beartype
def __radd__(self, other: RealLike) -> "RollOutcome":
    try:
        return self.rmap(other, __add__)
    except NotImplementedError:
        return NotImplemented

__rand__(other: SupportsInt) -> RollOutcome

Source code in dyce/r.py
2336
2337
2338
2339
2340
2341
@beartype
def __rand__(self, other: SupportsInt) -> "RollOutcome":
    try:
        return self.rmap(as_int(other), __and__)
    except (NotImplementedError, TypeError):
        return NotImplemented

__repr__() -> str

Source code in dyce/r.py
2160
2161
2162
2163
2164
2165
    @beartype
    def __repr__(self) -> str:
        return f"""{type(self).__name__}(
  value={repr(self.value)},
  sources=({_seq_repr(self.sources)}),
)"""

__rfloordiv__(other: RealLike) -> RollOutcome

Source code in dyce/r.py
2290
2291
2292
2293
2294
2295
@beartype
def __rfloordiv__(self, other: RealLike) -> "RollOutcome":
    try:
        return self.rmap(other, __floordiv__)
    except NotImplementedError:
        return NotImplemented

__rmod__(other: RealLike) -> RollOutcome

Source code in dyce/r.py
2304
2305
2306
2307
2308
2309
@beartype
def __rmod__(self, other: RealLike) -> "RollOutcome":
    try:
        return self.rmap(other, __mod__)
    except NotImplementedError:
        return NotImplemented

__rmul__(other: RealLike) -> RollOutcome

Source code in dyce/r.py
2262
2263
2264
2265
2266
2267
@beartype
def __rmul__(self, other: RealLike) -> "RollOutcome":
    try:
        return self.rmap(other, __mul__)
    except NotImplementedError:
        return NotImplemented

__ror__(other: SupportsInt) -> RollOutcome

Source code in dyce/r.py
2372
2373
2374
2375
2376
2377
@beartype
def __ror__(self, other: SupportsInt) -> "RollOutcome":
    try:
        return self.rmap(as_int(other), __or__)
    except (NotImplementedError, TypeError):
        return NotImplemented

__rpow__(other: RealLike) -> RollOutcome

Source code in dyce/r.py
2318
2319
2320
2321
2322
2323
@beartype
def __rpow__(self, other: RealLike) -> "RollOutcome":
    try:
        return self.rmap(other, __pow__)
    except NotImplementedError:
        return NotImplemented

__rsub__(other: RealLike) -> RollOutcome

Source code in dyce/r.py
2248
2249
2250
2251
2252
2253
@beartype
def __rsub__(self, other: RealLike) -> "RollOutcome":
    try:
        return self.rmap(other, __sub__)
    except NotImplementedError:
        return NotImplemented

__rtruediv__(other: RealLike) -> RollOutcome

Source code in dyce/r.py
2276
2277
2278
2279
2280
2281
@beartype
def __rtruediv__(self, other: RealLike) -> "RollOutcome":
    try:
        return self.rmap(other, __truediv__)
    except NotImplementedError:
        return NotImplemented

__rxor__(other: SupportsInt) -> RollOutcome

Source code in dyce/r.py
2354
2355
2356
2357
2358
2359
@beartype
def __rxor__(self, other: SupportsInt) -> "RollOutcome":
    try:
        return self.rmap(as_int(other), __xor__)
    except (NotImplementedError, TypeError):
        return NotImplemented

__sub__(other: _RollOutcomeOperandT) -> RollOutcome

Source code in dyce/r.py
2241
2242
2243
2244
2245
2246
@beartype
def __sub__(self, other: _RollOutcomeOperandT) -> "RollOutcome":
    try:
        return self.map(__sub__, other)
    except NotImplementedError:
        return NotImplemented

__truediv__(other: _RollOutcomeOperandT) -> RollOutcome

Source code in dyce/r.py
2269
2270
2271
2272
2273
2274
@beartype
def __truediv__(self, other: _RollOutcomeOperandT) -> "RollOutcome":
    try:
        return self.map(__truediv__, other)
    except NotImplementedError:
        return NotImplemented

__xor__(other: Union[RollOutcome, SupportsInt]) -> RollOutcome

Source code in dyce/r.py
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
@beartype
# TODO(posita): See <https://github.com/beartype/beartype/issues/152>
def __xor__(self, other: Union["RollOutcome", SupportsInt]) -> "RollOutcome":
    try:
        if isinstance(other, SupportsInt):
            other = as_int(other)

        return self.map(__xor__, other)
    except (NotImplementedError, TypeError):
        return NotImplemented

adopt(sources: Iterable[RollOutcome] = (), coalesce_mode: CoalesceMode = CoalesceMode.REPLACE) -> RollOutcome

Creates and returns a new roll outcome identical to this roll outcome, but with sources replacing or appended to this roll outcome’s sources in accordance with coalesce_mode.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
>>> from dyce.r import CoalesceMode
>>> orig = RollOutcome(1, sources=(RollOutcome(2),)) ; orig
RollOutcome(
  value=1,
  sources=(
    RollOutcome(
      value=2,
      sources=(),
    ),
  ),
)
>>> orig.adopt((RollOutcome(3),), coalesce_mode=CoalesceMode.REPLACE)
RollOutcome(
  value=1,
  sources=(
    RollOutcome(
      value=3,
      sources=(),
    ),
  ),
)
>>> orig.adopt((RollOutcome(3),), coalesce_mode=CoalesceMode.APPEND)
RollOutcome(
  value=1,
  sources=(
    RollOutcome(
      value=2,
      sources=(),
    ),
    RollOutcome(
      value=3,
      sources=(),
    ),
  ),
)
Source code in dyce/r.py
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
@beartype
def adopt(
    self,
    sources: Iterable["RollOutcome"] = (),
    coalesce_mode: CoalesceMode = CoalesceMode.REPLACE,
) -> "RollOutcome":
    r"""
    Creates and returns a new roll outcome identical to this roll outcome, but with
    *sources* replacing or appended to this roll outcome’s sources in accordance
    with *coalesce_mode*.

    ``` python
    >>> from dyce.r import CoalesceMode
    >>> orig = RollOutcome(1, sources=(RollOutcome(2),)) ; orig
    RollOutcome(
      value=1,
      sources=(
        RollOutcome(
          value=2,
          sources=(),
        ),
      ),
    )
    >>> orig.adopt((RollOutcome(3),), coalesce_mode=CoalesceMode.REPLACE)
    RollOutcome(
      value=1,
      sources=(
        RollOutcome(
          value=3,
          sources=(),
        ),
      ),
    )
    >>> orig.adopt((RollOutcome(3),), coalesce_mode=CoalesceMode.APPEND)
    RollOutcome(
      value=1,
      sources=(
        RollOutcome(
          value=2,
          sources=(),
        ),
        RollOutcome(
          value=3,
          sources=(),
        ),
      ),
    )

    ```
    """
    if coalesce_mode is CoalesceMode.REPLACE:
        adopted_sources = sources
    elif coalesce_mode is CoalesceMode.APPEND:
        adopted_sources = chain(self.sources, sources)
    else:
        assert False, f"unrecognized substitution mode {self.coalesce_mode!r}"

    adopted_roll_outcome = type(self)(self.value, adopted_sources)
    adopted_roll_outcome._roll = self._roll

    return adopted_roll_outcome

eq(other: _RollOutcomeOperandT) -> RollOutcome

Source code in dyce/r.py
2595
2596
2597
2598
2599
2600
2601
2602
@beartype
def eq(self, other: _RollOutcomeOperandT) -> "RollOutcome":
    if isinstance(other, RollOutcome):
        return type(self)(bool(__eq__(self, other)), sources=(self, other))
    elif self.value is not None:
        return type(self)(bool(__eq__(self.value, other)), sources=(self,))
    else:
        raise ValueError(f"unable to compare {self} to {other}")

euthanize() -> RollOutcome

Shorthand for self.umap(lambda operand: None).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
>>> two = RollOutcome(2)
>>> two.euthanize()
RollOutcome(
  value=None,
  sources=(
    RollOutcome(
      value=2,
      sources=(),
    ),
  ),
)

See the umap method.

Source code in dyce/r.py
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
@beartype
def euthanize(self) -> "RollOutcome":
    r"""
    Shorthand for ``#!python self.umap(lambda operand: None)``.

    ``` python
    >>> two = RollOutcome(2)
    >>> two.euthanize()
    RollOutcome(
      value=None,
      sources=(
        RollOutcome(
          value=2,
          sources=(),
        ),
      ),
    )

    ```

    See the [``umap`` method][dyce.r.RollOutcome.umap].
    """

    def _euthanize(operand: Optional[RealLike]) -> None:
        pass

    return self.umap(_euthanize)

ge(other: _RollOutcomeOperandT) -> RollOutcome

Source code in dyce/r.py
2620
2621
2622
2623
2624
2625
2626
2627
@beartype
def ge(self, other: _RollOutcomeOperandT) -> "RollOutcome":
    if isinstance(other, RollOutcome):
        return type(self)(bool(__ge__(self, other)), sources=(self, other))
    elif self.value is not None:
        return type(self)(bool(__ge__(self.value, other)), sources=(self,))
    else:
        raise ValueError(f"unable to compare {self} to {other}")

gt(other: _RollOutcomeOperandT) -> RollOutcome

Source code in dyce/r.py
2611
2612
2613
2614
2615
2616
2617
2618
@beartype
def gt(self, other: _RollOutcomeOperandT) -> "RollOutcome":
    if isinstance(other, RollOutcome):
        return type(self)(bool(__gt__(self, other)), sources=(self, other))
    elif self.value is not None:
        return type(self)(bool(__gt__(self.value, other)), sources=(self,))
    else:
        raise ValueError(f"unable to compare {self} to {other}")

is_even() -> RollOutcome

Shorthand for: self.umap(dyce.types.is_even).

See the umap method.

Source code in dyce/r.py
2629
2630
2631
2632
2633
2634
2635
2636
@beartype
def is_even(self) -> "RollOutcome":
    r"""
    Shorthand for: ``#!python self.umap(dyce.types.is_even)``.

    See the [``umap`` method][dyce.r.RollOutcome.umap].
    """
    return self.umap(is_even)

is_odd() -> RollOutcome

Shorthand for: self.umap(dyce.types.is_even).

See the umap method.

Source code in dyce/r.py
2638
2639
2640
2641
2642
2643
2644
2645
@beartype
def is_odd(self) -> "RollOutcome":
    r"""
    Shorthand for: ``#!python self.umap(dyce.types.is_even)``.

    See the [``umap`` method][dyce.r.RollOutcome.umap].
    """
    return self.umap(is_odd)

le(other: _RollOutcomeOperandT) -> RollOutcome

Source code in dyce/r.py
2586
2587
2588
2589
2590
2591
2592
2593
@beartype
def le(self, other: _RollOutcomeOperandT) -> "RollOutcome":
    if isinstance(other, RollOutcome):
        return type(self)(bool(__le__(self, other)), sources=(self, other))
    elif self.value is not None:
        return type(self)(bool(__le__(self.value, other)), sources=(self,))
    else:
        raise ValueError(f"unable to compare {self} to {other}")

lt(other: _RollOutcomeOperandT) -> RollOutcome

Source code in dyce/r.py
2577
2578
2579
2580
2581
2582
2583
2584
@beartype
def lt(self, other: _RollOutcomeOperandT) -> "RollOutcome":
    if isinstance(other, RollOutcome):
        return type(self)(bool(__lt__(self, other)), sources=(self, other))
    elif self.value is not None:
        return type(self)(bool(__lt__(self.value, other)), sources=(self,))
    else:
        raise ValueError(f"unable to compare {self} to {other}")

map(bin_op: _BinaryOperatorT, right_operand: _RollOutcomeOperandT) -> RollOutcome

Applies bin_op to the value of this roll outcome as the left operand and right_operand as the right. Shorthands exist for many arithmetic operators and comparators.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
>>> import operator
>>> two = RollOutcome(2)
>>> two.map(operator.__pow__, 10)
RollOutcome(
  value=1024,
  sources=(
    RollOutcome(
      value=2,
      sources=(),
    ),
  ),
)
>>> two.map(operator.__pow__, 10) == two ** 10
True
Source code in dyce/r.py
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
@beartype
def map(
    self,
    bin_op: _BinaryOperatorT,
    right_operand: _RollOutcomeOperandT,
) -> "RollOutcome":
    r"""
    Applies *bin_op* to the value of this roll outcome as the left operand and
    *right_operand* as the right. Shorthands exist for many arithmetic operators and
    comparators.

    ``` python
    >>> import operator
    >>> two = RollOutcome(2)
    >>> two.map(operator.__pow__, 10)
    RollOutcome(
      value=1024,
      sources=(
        RollOutcome(
          value=2,
          sources=(),
        ),
      ),
    )
    >>> two.map(operator.__pow__, 10) == two ** 10
    True

    ```
    """
    if isinstance(right_operand, RollOutcome):
        sources: tuple[RollOutcome, ...] = (self, right_operand)
        right_operand_value: Optional[RealLike] = right_operand.value
    else:
        sources = (self,)
        right_operand_value = right_operand

    if isinstance(right_operand_value, RealLike):
        return type(self)(bin_op(self.value, right_operand_value), sources)
    else:
        raise NotImplementedError

ne(other: _RollOutcomeOperandT) -> RollOutcome

Source code in dyce/r.py
2604
2605
2606
2607
2608
2609
@beartype
def ne(self, other: _RollOutcomeOperandT) -> "RollOutcome":
    if isinstance(other, RollOutcome):
        return type(self)(bool(__ne__(self, other)), sources=(self, other))
    else:
        return type(self)(bool(__ne__(self.value, other)), sources=(self,))

rmap(left_operand: RealLike, bin_op: _BinaryOperatorT) -> RollOutcome

Analogous to the map method, but where the caller supplies left_operand.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
>>> import operator
>>> two = RollOutcome(2)
>>> two.rmap(10, operator.__pow__)
RollOutcome(
  value=100,
  sources=(
    RollOutcome(
      value=2,
      sources=(),
    ),
  ),
)
>>> two.rmap(10, operator.__pow__) == 10 ** two
True

Note

The positions of left_operand and bin_op are different from map method. This is intentional and serves as a reminder of operand ordering.

Source code in dyce/r.py
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
@beartype
def rmap(self, left_operand: RealLike, bin_op: _BinaryOperatorT) -> "RollOutcome":
    r"""
    Analogous to the [``map`` method][dyce.r.RollOutcome.map], but where the caller
    supplies *left_operand*.

    ``` python
    >>> import operator
    >>> two = RollOutcome(2)
    >>> two.rmap(10, operator.__pow__)
    RollOutcome(
      value=100,
      sources=(
        RollOutcome(
          value=2,
          sources=(),
        ),
      ),
    )
    >>> two.rmap(10, operator.__pow__) == 10 ** two
    True

    ```

    !!! note

        The positions of *left_operand* and *bin_op* are different from
        [``map`` method][dyce.r.RollOutcome.map]. This is intentional and serves as
        a reminder of operand ordering.
    """
    if isinstance(left_operand, RealLike):
        return type(self)(bin_op(left_operand, self.value), sources=(self,))
    else:
        raise NotImplementedError

umap(un_op: _UnaryOperatorT) -> RollOutcome

Applies un_op to the value of this roll outcome. Shorthands exist for many arithmetic operators and comparators.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
>>> import operator
>>> two_neg = RollOutcome(-2)
>>> two_neg.umap(operator.__neg__)
RollOutcome(
  value=2,
  sources=(
    RollOutcome(
      value=-2,
      sources=(),
    ),
  ),
)
>>> two_neg.umap(operator.__neg__) == -two_neg
True
Source code in dyce/r.py
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
@beartype
def umap(
    self,
    un_op: _UnaryOperatorT,
) -> "RollOutcome":
    r"""
    Applies *un_op* to the value of this roll outcome. Shorthands exist for many
    arithmetic operators and comparators.

    ``` python
    >>> import operator
    >>> two_neg = RollOutcome(-2)
    >>> two_neg.umap(operator.__neg__)
    RollOutcome(
      value=2,
      sources=(
        RollOutcome(
          value=-2,
          sources=(),
        ),
      ),
    )
    >>> two_neg.umap(operator.__neg__) == -two_neg
    True

    ```
    """
    return type(self)(un_op(self.value), sources=(self,))

RollWalkerVisitor

Experimental

This class (and its descendants) should be considered experimental and may change or disappear in future versions.

Abstract visitor interface for use with walk called for each Roll object found.

Source code in dyce/r.py
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
class RollWalkerVisitor:
    r"""
    !!! warning "Experimental"

        This class (and its descendants) should be considered experimental and may
        change or disappear in future versions.

    Abstract visitor interface for use with [``walk``][dyce.r.walk] called for each
    [``Roll`` object][dyce.r.Roll] found.
    """
    __slots__: Any = ()

    # ---- Overrides -------------------------------------------------------------------

    @abstractmethod
    def on_roll(self, roll: Roll, parents: Iterator[Roll]) -> None:
        ...

__slots__: Any = () class-attribute instance-attribute

on_roll(roll: Roll, parents: Iterator[Roll]) -> None abstractmethod

Source code in dyce/r.py
2957
2958
2959
@abstractmethod
def on_roll(self, roll: Roll, parents: Iterator[Roll]) -> None:
    ...

RollerWalkerVisitor

Experimental

This class (and its descendants) should be considered experimental and may change or disappear in future versions.

Abstract visitor interface for use with walk called for each R object found.

Source code in dyce/r.py
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
class RollerWalkerVisitor:
    r"""
    !!! warning "Experimental"

        This class (and its descendants) should be considered experimental and may
        change or disappear in future versions.

    Abstract visitor interface for use with [``walk``][dyce.r.walk] called for each
    [``R`` object][dyce.r.R] found.
    """
    __slots__: Any = ()

    # ---- Overrides -------------------------------------------------------------------

    @abstractmethod
    def on_roller(self, r: R, parents: Iterator[R]) -> None:
        ...

__slots__: Any = () class-attribute instance-attribute

on_roller(r: R, parents: Iterator[R]) -> None abstractmethod

Source code in dyce/r.py
2997
2998
2999
@abstractmethod
def on_roller(self, r: R, parents: Iterator[R]) -> None:
    ...

walk(root: Union[Roll, R, RollOutcome], visitor: Union[RollWalkerVisitor, RollerWalkerVisitor, RollOutcomeWalkerVisitor]) -> None

Experimental

This function should be considered experimental and may change or disappear in future versions.

Walks through root, calling visitor for each matching object. No ordering guarantees are made.

On the current implementation

walk performs a breadth-first traversal of root, assembling a secondary index of referencing objects (parents). Visitors are called back grouped first by type, then by order encountered.

Source code in dyce/r.py
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
@experimental
@beartype
def walk(
    root: Union[Roll, R, RollOutcome],
    visitor: Union[RollWalkerVisitor, RollerWalkerVisitor, RollOutcomeWalkerVisitor],
) -> None:
    r"""
    !!! warning "Experimental"

        This function should be considered experimental and may change or disappear in
        future versions.

    Walks through *root*, calling *visitor* for each matching object. No ordering
    guarantees are made.

    !!! info "On the current implementation"

        ``#!python walk`` performs a breadth-first traversal of *root*, assembling a
        secondary index of referencing objects (parents). Visitors are called back
        grouped first by type, then by order encountered.
    """
    rolls: dict[int, Roll] = {}
    rollers: dict[int, R] = {}
    roll_outcomes: dict[int, RollOutcome] = {}
    roll_parent_ids: defaultdict[int, set[int]] = defaultdict(set)
    roller_parent_ids: defaultdict[int, set[int]] = defaultdict(set)
    roll_outcome_parent_ids: defaultdict[int, set[int]] = defaultdict(set)
    queue = deque((root,))
    roll: Roll
    r: R
    roll_outcome: RollOutcome

    while queue:
        obj = queue.popleft()

        if isinstance(obj, Roll):
            roll = obj

            if id(roll) not in rolls:
                rolls[id(roll)] = roll

                queue.append(roll.r)

                for i, roll_outcome in enumerate(roll):
                    queue.append(roll_outcome)

                for source_roll in roll.source_rolls:
                    roll_parent_ids[id(source_roll)].add(id(roll))
                    queue.append(source_roll)
        elif isinstance(obj, R):
            r = obj

            if id(r) not in rollers:
                rollers[id(r)] = r

                for source_r in r.sources:
                    roller_parent_ids[id(source_r)].add(id(r))
                    queue.append(source_r)
        elif isinstance(obj, RollOutcome):
            roll_outcome = obj

            if id(roll_outcome) not in roll_outcomes:
                roll_outcomes[id(roll_outcome)] = roll_outcome

                for source_roll_outcome in roll_outcome.sources:
                    roll_outcome_parent_ids[id(source_roll_outcome)].add(
                        id(roll_outcome)
                    )
                    queue.append(source_roll_outcome)

    if rolls and isinstance(visitor, RollWalkerVisitor):
        for roll_id, roll in rolls.items():
            visitor.on_roll(roll, (rolls[i] for i in roll_parent_ids[roll_id]))

    if rollers and isinstance(visitor, RollerWalkerVisitor):
        for r_id, r in rollers.items():
            visitor.on_roller(r, (rollers[i] for i in roller_parent_ids[r_id]))

    if roll_outcomes and isinstance(visitor, RollOutcomeWalkerVisitor):
        for roll_outcome_id, roll_outcome in roll_outcomes.items():
            visitor.on_roll_outcome(
                roll_outcome,
                (roll_outcomes[i] for i in roll_outcome_parent_ids[roll_outcome_id]),
            )