The constrainedrandom package

This is the documentation generated from the code. It is intended as developer-facing documentation.

User-facing classes

These classes are user-facing and the API should remain the same. If changes are necessary, this should result in a major version increment.

Internal classes

These classes are internal-facing and the design can change if required.

Miscellaneous utilities for the constrainedrandom package.

exception constrainedrandom.utils.RandomizationError

Bases: Exception

Denotes that a randomization attempt has failed.

constrainedrandom.utils.is_pure(function: Callable) bool

Determine whether a function is “pure”, i.e. its return value is only influenced by its arguments when it is called and by nothing else..

Parameters:

function – Callable to determine whether it is pure.

Returns:

True if “pure”, False otherwise,

constrainedrandom.utils.unique(list_variable: Iterable[Any]) bool

Optimal function for testing uniqueness of values in a list. Useful constraint on a list. O(N) time complexity where N is list length, but also O(N) worst-case space complexity. Usually what you want rather than O(N**2) time compexity and O(1) space.

Parameters:

list_variable – A list (or any iterable).

Returns:

True if every element in the list is unique, False otherwise.

constrainedrandom.random.dist(dist_dict: Dict[Any, int], _random: Random | None = None) Any

Random distribution. As weighted_choice(), but allows range to be used as a key to the dictionary, which if chosen is then evaluated as a random range.

Parameters:
  • dist_dict – A dict containing the possible values as keys and relative weights as values. If a range is supplied as a key, it will be evaluated as a random range.

  • _random – Instance of random generator object to use. If not supplied, use global Python random module.

Returns:

One of the keys of dist_dict chosen at random, based on weighting. If the key is a range, evaluate the range as a random range before returning.

Example:

# 0 will be chosen 25% of the time, a value in the range 1 to 9 25% of the time
# and 'foo' 50% of the time
value = dist({0: 25, range(1, 10): 25, 'foo': 50})
constrainedrandom.random.weighted_choice(choices_dict: Dict[Any, int], _random: Random | None = None) Any

Wrapper around random.choices, allowing the user to specify weights in a dictionary.

Parameters:
  • choices_dict – A dict containing the possible values as keys and relative weights as values.

  • _random – Instance of random generator object to use. If not supplied, use global Python random module.

Returns:

One of the keys of choices_dict chosen at random, based on weighting.

Example:

# 0 will be chosen 25% of the time, 1 25% of the time and 'foo' 50% of the time
value = weighted_choice({0: 25, 1: 25, 'foo': 50})