From e75170261081245cdcaf7ed6833fcce9483884df Mon Sep 17 00:00:00 2001 From: evilchili Date: Sun, 24 Dec 2023 11:48:39 -0800 Subject: [PATCH] adding set_frequency() --- random_sets/datasources.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/random_sets/datasources.py b/random_sets/datasources.py index 16638b9..0075d2a 100644 --- a/random_sets/datasources.py +++ b/random_sets/datasources.py @@ -4,6 +4,12 @@ import yaml from typing import IO +class UnknownFrequencyError(Exception): + """ + Thrown when attempting to set a datasource's fequency without a frequency table in the metadat. + """ + + class DataSource: """ Represents a yaml data source used to generate roll tables. @@ -66,6 +72,19 @@ class DataSource: frequencies.update(**self.metadata['frequencies']) self.frequencies = frequencies[self.frequency] + def set_frequency(self, frequency: str) -> None: + """ + Select a new frequency distribution from the data source metadata. + """ + if 'frequencies' not in self.metadata: + raise UnknownFrequencyError( + "Cannnot set a new frequency because there is no frequency table in the metadata." + ) + if frequency not in self.metadata['frequencies']: + raise UnknownFrequencyError(f"{frequency} is not present in the frequency table.") + self.frequency = frequency + self.init_frequencies() + def random_frequencies(self, count: int = 1) -> list: """ Choose random option names from the frequency table.