dicing package¶
dicing — typed, extensible dice library for tabletop RPGs.
Everything listed in __all__ is the public API and can be imported directly:
from dicing import d6, d20, DicePool, adv, kh, parse_dice_notation
Core: Dice and DicePool¶
Core dice model: Dice, DicePool and dice mechanics (adv/dis, keep/drop, throws).
roll() always returns a single int — for a die and for a pool (sum of its dice).
Individual results of a pool are available through DicePool.roll_each().
Examples in this module use SeededRandomStrategy, so every
roll shown below is reproducible and checked by doctest.
Example
>>> from dicing import Dice, SeededRandomStrategy
>>> d20 = Dice(1, 20, SeededRandomStrategy(42))
>>> d20.roll()
4
>>> d20.check_success(15)
False
Warning
Creating dice with invalid sides (min >= max) raises DiceInvalidSidesError (a ValueError).
- class dicing.dice.Dice(_smallest_side, _biggest_side, _randomization_strategy=<factory>, _roll_strategy=<factory>)¶
Bases:
DiceableClass for immutable dice.
Negative sides are allowed (e.g. Fate dice
Dice(-1, 1)) as long as smallest < biggest.- Variables:
_smallest_side (int) – Smallest side of the die
_biggest_side (int) – Largest side of the die
_randomization_strategy (RandomStrategy) – Random number generation strategy
_roll_strategy (RollStrategy) – Dice rolling strategy
- Raises:
DiceInvalidSidesError – If smallest side is not less than biggest side
- Parameters:
_smallest_side (int)
_biggest_side (int)
_randomization_strategy (Final[RandomStrategy])
_roll_strategy (Final[RollStrategy])
- property biggest_side: int¶
Get the largest side of the die.
- Returns:
Largest side value (read-only)
- Return type:
int
Note
Value is set during instance creation
- check_success(check, inserted_roll_strategy=None)¶
Check success against a target number.
- Parameters:
check (int) – Target number to beat
inserted_roll_strategy (RollStrategy | None) – Optional roll strategy override
- Returns:
True if roll meets/exceeds target, False otherwise
- Return type:
bool
- classmethod from_dict(data)¶
Create a Dice instance from a dictionary.
- Parameters:
data (dict[str, int]) – Dictionary with keys ‘smallest_side’ and ‘biggest_side’
- Returns:
New Dice instance
- Return type:
- Raises:
KeyError – If required keys are missing
TypeError – If values are not integers
Example
>>> dice_data = {"smallest_side": 1, "biggest_side": 6} >>> d6 = Dice.from_dict(dice_data) >>> isinstance(d6, Dice) True
- property randomization_strategy: RandomStrategy¶
Get the random number generation strategy.
- Returns:
Randomization strategy instance
- Return type:
Note
Value is set during instance creation
- roll(modifier=0, inserted_roll_strategy=None)¶
Roll the die with optional modifier.
- Parameters:
modifier (int) – Roll modifier to add
inserted_roll_strategy (RollStrategy | None) – Optional roll strategy override
- Returns:
Final roll result
- Return type:
int
- property roll_strategy: RollStrategy¶
Get the dice rolling strategy.
- Returns:
Roll strategy instance
- Return type:
Note
Value is set during instance creation
- property smallest_side: int¶
Get the smallest side of the die.
- Returns:
Smallest side value (read-only)
- Return type:
int
Note
Value is set during instance creation
- to_dict()¶
Serialize the Dice instance to a dictionary.
- Returns:
- Dictionary representation with keys:
’smallest_side’: int
’biggest_side’: int
- Return type:
dict
Example
>>> d6 = Dice(1, 6) >>> d6.to_dict() {'smallest_side': 1, 'biggest_side': 6}
Note
Strategy objects are not serialized as they are implementation details and typically not needed in API responses.
- class dicing.dice.DicePool(dices)¶
Bases:
DiceableClass for mutable dice pools.
Represents a collection of Dice objects, allowing dynamic addition and removal. Provides a unified interface similar to Dice for rolling and operations.
- Variables:
_dice_list (list[Dice]) – List of Dice instances in the pool
- Raises:
InvalidDiceInputError – If invalid items are added during initialization
- Parameters:
Example
A pool of three d6 (3d6):
>>> from dicing import SeededRandomStrategy, d6 >>> rng = SeededRandomStrategy(42) >>> pool = DicePool([d6(random_strategy=rng) for _ in range(3)]) >>> pool.roll() # sum of the dice 8 >>> pool.roll(modifier=2) # 3d6+2: the modifier is added to the sum once 13 >>> pool.roll_each() # individual results [2, 2, 6]
Note
DicePool is mutable, allowing addition/removal of dice after creation.
- __init__(dices)¶
Initialize the dice pool with given dice.
- Parameters:
dices (list[Dice] | Dice) – Single Dice or list of Dice to include in the pool
- Raises:
InvalidDiceInputError – If input contains invalid items
- Return type:
None
Example
>>> from dicing.aliases import d6 >>> pool = DicePool(d6()) # Single die pool >>> len(pool._dice_list) == 1 True >>> pool = DicePool([d6(), d6()]) >>> len(pool._dice_list) == 2 True
- add_dice(added_dice)¶
Add one or more dice to the pool.
- Parameters:
added_dice (Dice) – Single Dice or list of Dice to add
- Raises:
InvalidDiceInputError – If added items are invalid
- Return type:
None
Example
>>> from dicing.aliases import d6 >>> pool = DicePool(d6()) >>> pool.add_dice(d6()) >>> len(pool._dice_list) == 2 True
- check_success(check, inserted_roll_strategy=None)¶
Check success against a target number for the pool sum.
Rolls all dice in the pool, sums the results, and checks against the target.
- Parameters:
check (int) – Target number to beat
inserted_roll_strategy (RollStrategy | None) – Optional roll strategy override for all dice
- Returns:
True if sum meets/exceeds target, False otherwise
- Return type:
bool
- classmethod from_dict(data)¶
Create a DicePool instance from a dictionary.
- Parameters:
data (dict[str, list[dict[str, int]]]) – Dictionary with key ‘dice’ containing list of Dice dictionaries
- Returns:
New DicePool instance
- Return type:
- Raises:
KeyError – If required keys are missing
TypeError – If values have incorrect types
Example
>>> dice_data = { ... "dice": [ ... {"smallest_side": 1, "biggest_side": 6}, ... {"smallest_side": 1, "biggest_side": 20}, ... ] ... } >>> print(DicePool.from_dict(dice_data)) DicePool(2 dice: [1d6, 1d20])
- remove_dice(dice_to_remove)¶
Remove specified dice from the pool.
Removes the first occurrence of the matching dice.
- Parameters:
dice_to_remove (Dice) – Single Diceable or list of Diceable to remove
- Raises:
ValueError – If item not found in the pool
InvalidDiceInputError – If input is invalid
- Return type:
None
Example
>>> from dicing.aliases import d6 >>> pool = DicePool([d6(), d6()]) >>> dice = pool._dice_list[0] >>> pool.remove_dice(dice) >>> len(pool._dice_list) == 1 True
- remove_dice_by_index(index_of_dice)¶
Remove dice from the pool by index.
- Parameters:
index_of_dice (int) – Index of the dice to remove (0-based)
- Raises:
IndexError – If index is out of range
- Return type:
None
Example
>>> from dicing.aliases import d6 >>> pool = DicePool([d6(), d6()]) >>> pool.remove_dice_by_index(0) >>> len(pool._dice_list) == 1 True
- roll(modifier=0, inserted_roll_strategy=None)¶
Roll all dice and return the sum plus the modifier (
2d6+3).- Parameters:
modifier (int) – Added to the sum once (not to each die)
inserted_roll_strategy (RollStrategy | None) – Optional roll strategy override for all dice
- Returns:
Sum of all dice plus the modifier
- Return type:
int
- roll_each(inserted_roll_strategy=None)¶
Roll all dice and return the individual results.
- Parameters:
inserted_roll_strategy (RollStrategy | None) – Optional roll strategy override for all dice
- Returns:
One result per die, in pool order
- Return type:
list[int]
- to_dict()¶
Serialize the DicePool instance to a dictionary.
- Returns:
- Dictionary representation with key:
’dice’: list of serialized Dice dictionaries
- Return type:
dict
Example
>>> from dicing.aliases import d6, d20 >>> pool = DicePool([d6(), d20()]) >>> pool_dict = pool.to_dict() >>> len(pool_dict["dice"]) == 2 True >>> pool_dict["dice"][0]["biggest_side"] == 6 True
- class dicing.dice.Diceable¶
Bases:
ABCInterface for dice-like clasess.
- abstractmethod check_success(check, inserted_roll_strategy=None)¶
Check success against a target number.
- Parameters:
check (int) – Target number to beat
inserted_roll_strategy (RollStrategy | None) – Optional roll strategy override
- Returns:
True if roll meets/exceeds target, False otherwise
- Return type:
bool
- abstractmethod roll(modifier=0, inserted_roll_strategy=None)¶
Roll and return a single total.
- Parameters:
modifier (int) – Added to the total once
inserted_roll_strategy (RollStrategy | None) – Optional roll strategy override
- Returns:
Roll total with the modifier
- Return type:
int
- dicing.dice.adv(dices)¶
Return the maximum roll result from a collection of dice.
This function accepts either a single dice object or a collection of dice objects, rolls all dice, and returns the highest result obtained.
- Parameters:
dices (Dice | list[Dice]) – An object implementing the Dice interface, or an iterable collection of such objects.
- Returns:
The highest value among all dice roll results.
- Raises:
DiceOperationTypeError – If the provided argument is not a dice object or iterable collection, or if any element in the collection doesn’t implement the Dice interface.
- Return type:
int
Examples
>>> from dicing import SeededRandomStrategy, d6, d20 >>> rng = SeededRandomStrategy(42) >>> adv(d20(random_strategy=rng)) # single die: rolled twice, best result 4 >>> adv([d6(random_strategy=rng), d20(random_strategy=rng)]) # best of mixed dice 9
- dicing.dice.dh(dices, drop)¶
Drop the highest ‘drop’ rolls from the dice (equivalent to keep lowest n-drop).
Returns sorted list of remaining rolls (ascending). Handles drop=0 (all rolls) and drop=n (empty).
- dicing.dice.dis(dices)¶
Return the minimum roll result from a collection of dice.
This function accepts either a single dice object or a collection of dice objects, rolls all dice, and returns the lowest result obtained.
- Parameters:
dices (Dice | list[Dice]) – An object implementing the Dice interface, or an iterable collection of such objects.
- Returns:
The lowest value among all dice roll results.
- Raises:
DiceOperationTypeError – If the provided argument is not a dice object or iterable collection, or if any element in the collection doesn’t implement the Dice interface.
- Return type:
int
Examples
>>> from dicing import SeededRandomStrategy, d6, d20 >>> rng = SeededRandomStrategy(42) >>> dis(d20(random_strategy=rng)) # single die: rolled twice, worst result 1 >>> dis([d6(random_strategy=rng), d20(random_strategy=rng)]) # worst of mixed dice 6
- dicing.dice.dl(dices, drop)¶
Drop the lowest ‘drop’ rolls from the dice (equivalent to keep highest n-drop).
Returns sorted list of remaining rolls (descending). Handles drop=0 (all rolls) and drop=n (empty).
- dicing.dice.drop_highest_rolls(rolls, drop)¶
Drop the
drophighest of already rolled values; the rest is sorted ascending.- Parameters:
rolls (list[int])
drop (int)
- Return type:
list[int]
- dicing.dice.drop_lowest_rolls(rolls, drop)¶
Drop the
droplowest of already rolled values; the rest is sorted descending.- Parameters:
rolls (list[int])
drop (int)
- Return type:
list[int]
- dicing.dice.get_rolls(d)¶
Roll and return individual results: one value for a die, one per die for a pool.
- Parameters:
d (Diceable) – Diceable instance to roll
- Returns:
List of roll results
- Return type:
list[int]
Example
>>> from dicing import DicePool, SeededRandomStrategy, d6 >>> rng = SeededRandomStrategy(42) >>> get_rolls(d6(random_strategy=rng)) [6] >>> get_rolls(DicePool([d6(random_strategy=rng), d6(random_strategy=rng)])) [1, 1]
- dicing.dice.keep_highest_rolls(rolls, keep)¶
Keep the
keephighest of already rolled values, sorted descending.- Parameters:
rolls (list[int])
keep (int)
- Return type:
list[int]
- dicing.dice.keep_lowest_rolls(rolls, keep)¶
Keep the
keeplowest of already rolled values, sorted ascending.- Parameters:
rolls (list[int])
keep (int)
- Return type:
list[int]
- dicing.dice.kh(dices, keep)¶
Keep the highest ‘keep’ rolls from the dice.
Returns sorted list of kept rolls (descending). Efficient for large sets using heap.
- dicing.dice.kl(dices, keep)¶
Keep the lowest ‘keep’ rolls from the dice.
Returns sorted list of kept rolls (ascending). Efficient for large sets using heap.
- dicing.dice.throws(dice, count=1, roll_modificator=0)¶
Generate a sequence of dice roll results for a specified number of throws.
This function takes a single dice object, rolls it the specified number of times, and yields each roll result with an optional modifier applied.
- Parameters:
dice (Diceable) – An object implementing the Dice interface, with a roll method.
count (int) – The number of times to roll the dice (default: 1).
roll_modificator (int) – An integer to add to each roll result (default: 0).
- Yields:
The result of each dice roll, with the modifier applied.
- Raises:
NegativeThrowCountError – If the count of throws is negative.
InvalidDiceError – If the provided dice argument does not implement the Dice interface.
- Return type:
Generator[int, None, None]
Examples
>>> from dicing import DicePool, SeededRandomStrategy, d6, d20 >>> rng = SeededRandomStrategy(42) >>> list(throws(d6(random_strategy=rng), count=3)) # three rolls of a d6 [6, 1, 1] >>> list(throws(d20(random_strategy=rng), count=2, roll_modificator=3)) # two d20+3 [12, 11] >>> list(throws(DicePool([d6(random_strategy=rng), d6(random_strategy=rng)]), count=2)) # 2d6 twice [4, 7]
Strategies¶
Strategies of the Strategy pattern (GoF) used by Dice.
A die delegates two independent decisions to interchangeable objects:
where random numbers come from —
RandomStrategy:DefaultRandomStrategy(cryptographically strong, default),PseudoRandomStrategy(fastrandommodule),SeededRandomStrategy(reproducible — for tests, replays and documentation);how a roll is made —
RollStrategy:DefaultRoll,AdvantageRoll,DisadvantageRoll,MultipleRoll.
Both are typing.Protocol s, so any object with a matching method works — no inheritance needed.
Example
The same Dice class, without any changes, works with every source of randomness:
>>> from dicing import Dice, DefaultRandomStrategy, PseudoRandomStrategy, SeededRandomStrategy
>>> 1 <= Dice(1, 20, DefaultRandomStrategy()).roll() <= 20 # secure, unpredictable
True
>>> 1 <= Dice(1, 20, PseudoRandomStrategy()).roll() <= 20 # fast, unpredictable
True
>>> Dice(1, 20, SeededRandomStrategy(7)).roll() # reproducible
11
>>> Dice(1, 20, SeededRandomStrategy(7)).roll() # same seed -> same roll
11
A user-defined strategy plugs in the same way, e.g. a loaded die for a test:
>>> class AlwaysMax:
... def randint(self, smallest: int, biggest: int) -> int:
... return biggest
>>> Dice(1, 20, AlwaysMax()).roll()
20
The roll mechanics are swapped independently of the randomness:
>>> from dicing import AdvantageRoll, DisadvantageRoll
>>> d20 = Dice(1, 20, SeededRandomStrategy(7))
>>> d20.roll(inserted_roll_strategy=AdvantageRoll()) # best of two
11
>>> d20.roll(inserted_roll_strategy=DisadvantageRoll()) # worst of two
2
- class dicing.strategies.dice_strategies.AdvantageRoll¶
Bases:
objectRoll strategy that takes the highest of two dice rolls.
- class dicing.strategies.dice_strategies.DefaultRandomStrategy¶
Bases:
objectCryptographically strong random number strategy using system RNG.
- __init__()¶
Initialize the strategy with a secure random number generator.
- Return type:
None
- randint(smallest, biggest)¶
Generate a cryptographically strong random integer.
- Parameters:
smallest (int) – Lower bound (inclusive)
biggest (int) – Upper bound (inclusive)
- Returns:
Secure random integer in range [smallest, biggest]
- Return type:
int
- class dicing.strategies.dice_strategies.DefaultRoll¶
Bases:
objectStandard single-die rolling strategy.
- class dicing.strategies.dice_strategies.DisadvantageRoll¶
Bases:
objectRoll strategy that takes the lowest of two dice rolls.
- class dicing.strategies.dice_strategies.MultipleRoll(times=1)¶
Bases:
objectRoll strategy for multiple dice with instance caching.
- Parameters:
times (int)
- Return type:
- classmethod clear_instances()¶
Clear all cached instances of the class.
Note
Useful for resetting the instance cache during runtime.
- Return type:
None
- roll(dice, modifier=0)¶
Roll multiple dice and sum the results.
- Parameters:
dice (Dice) – Dice instance to roll
modifier (int) – Modifier to add to the total
- Returns:
Sum of all dice rolls + modifier
- Return type:
int
Example
>>> from dicing import Dice, SeededRandomStrategy >>> d6 = Dice(1, 6, SeededRandomStrategy(42)) >>> MultipleRoll(3).roll(d6) # the same die rolled 3 times and summed, like 3d6 8
- property times: int¶
Get the number of dice to roll.
- Returns:
Number of dice (read-only)
- class dicing.strategies.dice_strategies.PseudoRandomStrategy¶
Bases:
objectStandard pseudo-random number strategy using Python’s random module.
- randint(smallest, biggest)¶
Generate a pseudo-random integer.
- Parameters:
smallest (int) – Lower bound (inclusive)
biggest (int) – Upper bound (inclusive)
- Returns:
Pseudo-random integer in range [smallest, biggest]
- Return type:
int
Note
Not suitable for cryptographic purposes
- class dicing.strategies.dice_strategies.RandomStrategy(*args, **kwargs)¶
Bases:
ProtocolProtocol for random number generation strategies.
- randint(smallest, biggest)¶
Generate a random integer between smallest and biggest (inclusive).
- Parameters:
smallest (int) – Lower bound (inclusive)
biggest (int) – Upper bound (inclusive)
- Returns:
Random integer in range [smallest, biggest]
- Return type:
int
- class dicing.strategies.dice_strategies.RollStrategy(*args, **kwargs)¶
Bases:
ProtocolProtocol for dice rolling strategies.
- class dicing.strategies.dice_strategies.SeededRandomStrategy(seed)¶
Bases:
objectReproducible pseudo-random strategy: the same seed gives the same sequence of numbers.
Each instance owns its own generator, so it doesn’t affect (and isn’t affected by) the global
randomstate. Share one instance between dice to make a whole pool or parsed expression reproducible. Not suitable for cryptographic purposes.- Parameters:
seed (int | str | bytes)
- __init__(seed)¶
Initialize the strategy with a private generator.
- Parameters:
seed (int | str | bytes) – Seed of the generator
- Return type:
None
- randint(smallest, biggest)¶
Return the next number of the seeded sequence.
- Parameters:
smallest (int) – Lower bound (inclusive)
biggest (int) – Upper bound (inclusive)
- Returns:
Integer in range [smallest, biggest]
- Return type:
int
Aliases¶
Factory method with basic dice partial preset.
- dicing.aliases.dice_aliases.create_dice(smallest_side=1, biggest_side=4, *, random_strategy=None, roll_strategy=None)¶
Create a single die with specified parameters.
- Parameters:
smallest_side (int) – Smallest face value of the die
biggest_side (int) – Largest face value of the die
random_strategy (RandomStrategy) – Random number generation strategy
roll_strategy (RollStrategy) – Dice rolling strategy
- Returns:
Configured Dice instance
- Return type:
- dicing.aliases.dice_aliases.d10(*, random_strategy=None, roll_strategy=None)¶
Create a single die with specified parameters.
- Parameters:
smallest_side (int) – Smallest face value of the die
biggest_side (int) – Largest face value of the die
random_strategy (RandomStrategy) – Random number generation strategy
roll_strategy (RollStrategy) – Dice rolling strategy
- Returns:
Configured Dice instance
- Return type:
- dicing.aliases.dice_aliases.d10_percentages(*, random_strategy=None, roll_strategy=None)¶
Create a single die with specified parameters.
- Parameters:
smallest_side (int) – Smallest face value of the die
biggest_side (int) – Largest face value of the die
random_strategy (RandomStrategy) – Random number generation strategy
roll_strategy (RollStrategy) – Dice rolling strategy
- Returns:
Configured Dice instance
- Return type:
- dicing.aliases.dice_aliases.d12(*, random_strategy=None, roll_strategy=None)¶
Create a single die with specified parameters.
- Parameters:
smallest_side (int) – Smallest face value of the die
biggest_side (int) – Largest face value of the die
random_strategy (RandomStrategy) – Random number generation strategy
roll_strategy (RollStrategy) – Dice rolling strategy
- Returns:
Configured Dice instance
- Return type:
- dicing.aliases.dice_aliases.d20(*, random_strategy=None, roll_strategy=None)¶
Create a single die with specified parameters.
- Parameters:
smallest_side (int) – Smallest face value of the die
biggest_side (int) – Largest face value of the die
random_strategy (RandomStrategy) – Random number generation strategy
roll_strategy (RollStrategy) – Dice rolling strategy
- Returns:
Configured Dice instance
- Return type:
- dicing.aliases.dice_aliases.d4(*, random_strategy=None, roll_strategy=None)¶
Create a single die with specified parameters.
- Parameters:
smallest_side (int) – Smallest face value of the die
biggest_side (int) – Largest face value of the die
random_strategy (RandomStrategy) – Random number generation strategy
roll_strategy (RollStrategy) – Dice rolling strategy
- Returns:
Configured Dice instance
- Return type:
- dicing.aliases.dice_aliases.d6(*, random_strategy=None, roll_strategy=None)¶
Create a single die with specified parameters.
- Parameters:
smallest_side (int) – Smallest face value of the die
biggest_side (int) – Largest face value of the die
random_strategy (RandomStrategy) – Random number generation strategy
roll_strategy (RollStrategy) – Dice rolling strategy
- Returns:
Configured Dice instance
- Return type:
- dicing.aliases.dice_aliases.d8(*, random_strategy=None, roll_strategy=None)¶
Create a single die with specified parameters.
- Parameters:
smallest_side (int) – Smallest face value of the die
biggest_side (int) – Largest face value of the die
random_strategy (RandomStrategy) – Random number generation strategy
roll_strategy (RollStrategy) – Dice rolling strategy
- Returns:
Configured Dice instance
- Return type:
Factory method for DicePool class.
- dicing.aliases.dice_pool_aliases.create_dicepool(dice_list)¶
Create a DicePool instance from a single die or list of dice.
Normalizes input into a flat list of Dice instances and wraps them in a DicePool. Handles nested structures by recursively flattening lists and DicePool instances.
- Parameters:
dice_list (list[Dice] | Dice) – Single Dice instance or list of Dice instances (may include nested lists)
- Returns:
New DicePool containing all normalized dice
- Return type:
- Raises:
InvalidDiceInputError – If input contains non-Dice items
Example
>>> from dicing.aliases import d6, d20 >>> pool1 = create_dicepool(d6()) # Single die >>> len(pool1) == 1 True >>> pool2 = create_dicepool([d6(), d20(), [d6(), d6()]]) # Nested lists >>> len(pool2) == 4 True
Notation parser¶
Dice notation parser.
Parses notation strings like "2d6+3", "4d6kh3+1d4" or "1d20-1d4" into a lazy
ParsedRoll. Nothing is rolled during parsing: every call to ParsedRoll.roll()
makes a fresh roll of the whole expression.
The grammar lives in dice_grammar.lark; DiceTransformer walks the Lark parse tree
and delegates the actual construction to DiceTransformationEngine (Interpreter pattern).
- Supported syntax:
NdM/dM— N dice with M sides (N defaults to 1)kh,kl,dh,dlwith an optional amount (defaults to 1), chainable:4d6kh3dl1+and-between dice groups and integer modifiers
Example
>>> from dicing import SeededRandomStrategy, parse_dice_notation
>>> roll = parse_dice_notation("2d6+3", SeededRandomStrategy(42))
>>> len(roll.groups), roll.modifier # nothing is rolled yet
(1, 3)
>>> roll.roll() # each call is a fresh roll of the whole expression
10
>>> roll.roll()
10
- class dicing.utils.parser.dice_parser.DiceGroup(pool, keep_drop=(), sign=1)¶
Bases:
objectOne dice term of an expression, e.g.
4d6kh3or the1d4in1d20-1d4.- Variables:
pool (dicing.dice.DicePool) – Dice of the group
keep_drop (tuple[tuple[str, int], ...]) – Keep/drop operations applied to the rolls in order
sign (int) –
1if the group is added to the total,-1if subtracted
- Raises:
DiceInvalidAmountError – If keep/drop amounts don’t fit the number of dice (e.g.
4d6kh5)- Parameters:
pool (DicePool)
keep_drop (tuple[tuple[str, int], ...])
sign (int)
- keep_drop: tuple[tuple[str, int], ...]¶
- label()¶
Return the notation of the group without its sign.
Example
>>> from dicing import parse_dice_notation >>> [group.label() for group in parse_dice_notation("4d6kh3dl1 - d20").groups] ['4d6kh3dl1', '1d20']
- Return type:
str
- roll()¶
Roll the group and return the kept rolls (sign is not applied).
- Return type:
list[int]
- roll_detailed()¶
Roll the group and return every result together with the kept ones.
- Return type:
- sign: int¶
- class dicing.utils.parser.dice_parser.DiceTransformationEngine(random_strategy=None)¶
Bases:
objectBuilds
ParsedRollobjects from values extracted byDiceTransformer.- Parameters:
random_strategy (RandomStrategy | None)
- __init__(random_strategy=None)¶
Initialize the engine.
- Parameters:
random_strategy (RandomStrategy | None) – Random strategy for every created die; library default if None
- Return type:
None
- process_dice_expr(count, sides, keep_drop)¶
Build a single dice group such as
4d6kh3.- Raises:
ValueError – If the number of dice is not positive
DiceInvalidSidesError – If the die has fewer than 2 sides
DiceInvalidAmountError – If keep/drop amounts don’t fit the number of dice
- Parameters:
count (int | None)
sides (int)
keep_drop (list[tuple[str, int]])
- Return type:
- process_expr(items)¶
Combine
[term, op, term, op, term, ...]into one roll.+appends the right term;-appends it with negated dice groups and subtracts its modifier.- Raises:
TypeError – If the items don’t alternate between terms and operators
- Parameters:
items (list[ParsedRoll | str])
- Return type:
- static process_modifier(value)¶
Build an integer term such as the
3in2d6+3.- Parameters:
value (int)
- Return type:
- class dicing.utils.parser.dice_parser.DiceTransformer(random_strategy=None)¶
Bases:
TransformerLark transformer: turns parse tree nodes into values and passes them to the engine.
- Parameters:
random_strategy (RandomStrategy | None)
- __init__(random_strategy=None)¶
Initialize the transformer and its engine.
- Parameters:
random_strategy (RandomStrategy | None) – Random strategy for every created die; library default if None
- Return type:
None
- add()¶
Return the
+operator.- Return type:
str
- count(value)¶
Return the number of dice.
- Parameters:
value (Token)
- Return type:
int
- dice_expr(items)¶
Build a dice group from
[count | None, sides, *keep_drop].- Parameters:
items (list[int | tuple[str, int] | None])
- Return type:
- drop_highest(value)¶
Return
("dh", amount).- Parameters:
value (Token | None)
- Return type:
tuple[str, int]
- drop_lowest(value)¶
Return
("dl", amount).- Parameters:
value (Token | None)
- Return type:
tuple[str, int]
- expr(items)¶
Combine terms joined by
+/-.- Parameters:
items (list[ParsedRoll | str])
- Return type:
- keep_highest(value)¶
Return
("kh", amount).- Parameters:
value (Token | None)
- Return type:
tuple[str, int]
- keep_lowest(value)¶
Return
("kl", amount).- Parameters:
value (Token | None)
- Return type:
tuple[str, int]
- modifier(value)¶
Build an integer term.
- Parameters:
value (Token)
- Return type:
- sides(value)¶
Return the number of sides.
- Parameters:
value (Token)
- Return type:
int
- start(items)¶
Return the parsed expression.
- Parameters:
items (list[ParsedRoll])
- Return type:
- sub()¶
Return the
-operator.- Return type:
str
- class dicing.utils.parser.dice_parser.GroupRoll(label, sign, rolls, kept)¶
Bases:
objectDetailed result of rolling one
DiceGroup.- Variables:
label (str) – Notation of the group, e.g.
"4d6kh3"sign (int) –
1if the group is added to the total,-1if subtractedrolls (tuple[int, ...]) – Every die result, in roll order
kept (tuple[int, ...]) – Results left after keep/drop
- Parameters:
label (str)
sign (int)
rolls (tuple[int, ...])
kept (tuple[int, ...])
- property dropped: tuple[int, ...]¶
Results removed by keep/drop, in roll order.
- kept: tuple[int, ...]¶
- label: str¶
- rolls: tuple[int, ...]¶
- sign: int¶
- property subtotal: int¶
Signed sum of the kept results.
- to_dict()¶
Return a JSON-serializable representation.
- Return type:
dict[str, object]
- class dicing.utils.parser.dice_parser.ParsedRoll(groups=(), modifier=0)¶
Bases:
objectLazy result of parsing dice notation.
- Variables:
groups (tuple[dicing.utils.parser.dice_parser.DiceGroup, ...]) – Dice groups of the expression
modifier (int) – Sum of all integer terms, added to the total once
- Parameters:
groups (tuple[DiceGroup, ...])
modifier (int)
- modifier: int¶
- roll()¶
Roll every group and return the total: signed sums of kept rolls plus the modifier.
- Return type:
int
- roll_detailed()¶
Roll every group and return the full breakdown: all rolls, kept and dropped dice, total.
Example
>>> from dicing import SeededRandomStrategy, parse_dice_notation >>> result = parse_dice_notation("4d6kh3+2", SeededRandomStrategy(42)).roll_detailed() >>> group = result.groups[0] >>> group.label, group.rolls, group.kept, group.dropped ('4d6kh3', (6, 1, 1, 6), (6, 6, 1), (1,)) >>> result.total 15
- Return type:
- class dicing.utils.parser.dice_parser.RollResult(groups, modifier)¶
Bases:
objectDetailed result of rolling a whole
ParsedRoll.- Variables:
groups (tuple[dicing.utils.parser.dice_parser.GroupRoll, ...]) – Results of every dice group
modifier (int) – Sum of the integer terms
- Parameters:
groups (tuple[GroupRoll, ...])
modifier (int)
- modifier: int¶
- to_dict()¶
Return a JSON-serializable representation.
- Return type:
dict[str, object]
- property total: int¶
signed subtotals of all groups plus the modifier.
- Type:
Final result
- dicing.utils.parser.dice_parser.parse_dice_notation(notation, random_strategy=None)¶
Parse dice notation into a lazy
ParsedRoll.- Parameters:
notation (str) – Notation string, e.g.
"2d6+3","4d6kh3+1d4","1d20-1d4"random_strategy (RandomStrategy | None) – Random strategy for every die of the expression; library default if None. Passing a deterministic strategy makes the result reproducible (useful in tests).
- Returns:
Expression that can be rolled any number of times
- Return type:
- Raises:
lark.exceptions.LarkError – If the string doesn’t match the notation grammar
ValueError – If the expression is invalid (e.g.
0d6,1d1,4d6kh5)
Example
>>> from dicing import SeededRandomStrategy >>> parse_dice_notation("4d6kh3", SeededRandomStrategy(42)).roll() 13 >>> parse_dice_notation("1d20+5-1d4", SeededRandomStrategy(42)).roll() 8
Context managers¶
Context managers that temporarily roll a die (or a pool) with other strategies.
The context yields a copy of the die: the original is never changed. Only the strategies that are passed are replaced, the others are taken from the original die, so a seeded die stays reproducible when only its roll strategy is replaced:
>>> from dicing import AdvantageRoll, Dice, DiceContext, SeededRandomStrategy
>>> d20 = Dice(1, 20, SeededRandomStrategy(7))
>>> context = DiceContext(d20, replaced_roll_strategy=AdvantageRoll())
>>> with context as lucky_d20:
... [lucky_d20.roll() for _ in range(3)] # with advantage, same numbers on every run
[11, 13, 18]
>>> type(d20.roll_strategy).__name__ # the original die still rolls normally
'DefaultRoll'
>>> context.proxy_dice is None # the copy is released on exit
True
- class dicing.utils.context_managers.dice_base.BaseDiceContextManager(initial_dice, replaced_rng_strategy=None, replaced_roll_strategy=None)¶
Bases:
AbstractContextManager[Dice],ABCBase context manager for dice operations with strategy replacement.
- Parameters:
initial_dice (Dice)
replaced_rng_strategy (RandomStrategy | None)
replaced_roll_strategy (RollStrategy | None)
- __init__(initial_dice, replaced_rng_strategy=None, replaced_roll_strategy=None)¶
Initialize the context manager with dice and optional strategies.
- Parameters:
initial_dice (Dice) – The original dice instance to proxy
replaced_rng_strategy (RandomStrategy | None) – Optional RNG strategy to temporarily use (None keeps the die’s own)
replaced_roll_strategy (RollStrategy | None) – Optional roll strategy to temporarily use (None keeps the die’s own)
- Return type:
None
- abstractmethod on_enter()¶
Abstract method called when entering the context.
- Return type:
None
- abstractmethod on_exit(exc_type, exc_value, traceback)¶
Abstract method called when exiting the context.
- Parameters:
exc_type (type[BaseException] | None) – Exception type if an exception was raised
exc_value (BaseException | None) – Exception value if an exception was raised
traceback (TracebackType | None) – Traceback if an exception was raised
- Return type:
None
- class dicing.utils.context_managers.dice_base.BaseDicePoolContextManager(initial_pool, replaced_rng_strategy=None, replaced_roll_strategy=None)¶
Bases:
AbstractContextManager[DicePool],ABCBase context manager for dice pool operations with strategy replacement.
- Parameters:
initial_pool (DicePool)
replaced_rng_strategy (RandomStrategy | None)
replaced_roll_strategy (RollStrategy | None)
- __init__(initial_pool, replaced_rng_strategy=None, replaced_roll_strategy=None)¶
Initialize the context manager with dice pool and optional strategies.
- Parameters:
initial_pool (DicePool) – The original dice pool instance to proxy
replaced_rng_strategy (RandomStrategy | None) – Optional RNG strategy to temporarily use for all dice (None keeps each die’s own)
replaced_roll_strategy (RollStrategy | None) – Optional roll strategy to temporarily use for all dice (None keeps each die’s own)
- Return type:
None
- abstractmethod on_enter()¶
Abstract method called when entering the context.
- Return type:
None
- abstractmethod on_exit(exc_type, exc_value, traceback)¶
Abstract method called when exiting the context.
- Parameters:
exc_type (type[BaseException] | None) – Exception type if an exception was raised
exc_value (BaseException | None) – Exception value if an exception was raised
traceback (TracebackType | None) – Traceback if an exception was raised
- Return type:
None
- class dicing.utils.context_managers.dice_base.DiceContext(initial_dice, replaced_rng_strategy=None, replaced_roll_strategy=None)¶
Bases:
BaseDiceContextManagerSimple dice context manager with no additional behavior.
- Parameters:
initial_dice (Dice)
replaced_rng_strategy (RandomStrategy | None)
replaced_roll_strategy (RollStrategy | None)
- on_enter()¶
No-op implementation for context entry.
- Return type:
None
- on_exit(exc_type, exc_value, traceback)¶
No-op implementation for context exit.
- Parameters:
exc_type (type[BaseException] | None) – Exception type if an exception was raised
exc_value (BaseException | None) – Exception value if an exception was raised
traceback (TracebackType | None) – Traceback if an exception was raised
- Return type:
None
- class dicing.utils.context_managers.dice_base.DicePoolContext(initial_pool, replaced_rng_strategy=None, replaced_roll_strategy=None)¶
Bases:
BaseDicePoolContextManagerSimple dice pool context manager with no additional behavior.
- Parameters:
initial_pool (DicePool)
replaced_rng_strategy (RandomStrategy | None)
replaced_roll_strategy (RollStrategy | None)
- on_enter()¶
No-op implementation for context entry.
- Return type:
None
- on_exit(exc_type, exc_value, traceback)¶
No-op implementation for context exit.
- Parameters:
exc_type (type[BaseException] | None) – Exception type if an exception was raised
exc_value (BaseException | None) – Exception value if an exception was raised
traceback (TracebackType | None) – Traceback if an exception was raised
- Return type:
None
Exceptions¶
Custom exceptions for the dicing library, tailored for TRPG dice mechanics.
- exception dicing.exceptions.DiceCopyError¶
Bases:
TypeErrorRaised when
copy.deepcopyof a die fails because one of its strategies can’t be copied.A deep copy must not share state with the original: silently returning the same die would make two “independent” dice consume one random generator.
- exception dicing.exceptions.DiceInvalidAmountError¶
Bases:
ValueErrorRaised for invalid keep or drop amounts in TRPG dice operations.
In mechanics like ‘4d6 drop lowest’, amounts must be non-negative and <= number of dice.
- exception dicing.exceptions.DiceInvalidSidesError¶
Bases:
ValueErrorRaised when dice sides are invalid (min >= max).
Sides may be negative (e.g. Fate dice with faces -1..1), but min must be less than max.
- exception dicing.exceptions.DiceOperationTypeError¶
Bases:
TypeErrorRaised when invalid types are used in dice operations (e.g., d6 + ‘string’).
In TRPG formulas like ‘2d6 + 3’, operands must be ints or Dice.
- exception dicing.exceptions.InvalidDiceError¶
Bases:
TypeErrorRaised when input to throws isn’t a valid Dice object.
In TRPG, throws require a proper dice object.
- exception dicing.exceptions.InvalidDiceInputError¶
Bases:
TypeErrorRaised when input to functions isn’t Dice or iterable of Dice.
For TRPG mechanics like advantage rolls, input must be valid dice.
- exception dicing.exceptions.NegativeThrowCountError¶
Bases:
ValueErrorRaised when throw count is negative.
In TRPG, you can’t throw a dice a negative number of times.