From f828fd89341f36806996809a4b0038af0983b564 Mon Sep 17 00:00:00 2001 From: Paul Gierz Date: Mon, 7 Oct 2024 13:15:27 +0200 Subject: [PATCH] feat: warn if set method is used on rules instead of directly failing --- doc/pymorize_building_blocks.rst | 4 ++-- src/pymorize/rule.py | 19 ++++++++++++++----- 2 files changed, 16 insertions(+), 7 deletions(-) diff --git a/doc/pymorize_building_blocks.rst b/doc/pymorize_building_blocks.rst index 84a86f6..1048898 100644 --- a/doc/pymorize_building_blocks.rst +++ b/doc/pymorize_building_blocks.rst @@ -92,6 +92,6 @@ Rules can inherit global values. To do so, you should include them in the ``inhe pipelines: - my_pipeline - The rule ``my_rule`` will inherit the frequency ``mon`` from the global configuration, and can be accessed in - Python code as ``rule_spec.frequency``. +The rule ``my_rule`` will inherit the frequency ``mon`` from the global configuration, and can be accessed in +Python code as ``rule_spec.frequency``. diff --git a/src/pymorize/rule.py b/src/pymorize/rule.py index e0cea7b..c9e3b09 100644 --- a/src/pymorize/rule.py +++ b/src/pymorize/rule.py @@ -57,7 +57,7 @@ def __init__( def get(self, key, default=None): return getattr(self, key, default) - def set(self, key, value, force=False): + def set(self, key, value, force=False, warn=True): """ Set a new attribute for the object. @@ -70,6 +70,10 @@ def set(self, key, value, force=False): force : bool, optional If True, the attribute will be overwritten if it already exists. If False (default), an AttributeError will be raised if the attribute already exists. + warn : bool, optional + If True (default) a warning will be issued if the attribute already exists, and + it will not be overwritten. If False, an AttributeError will be raised if the attribute + already exists. Returns ------- @@ -79,12 +83,17 @@ def set(self, key, value, force=False): Raises ------ AttributeError - If the attribute already exists and force is False. + If the attribute already exists and force and warn are both False. """ if hasattr(self, key) and not force: - raise AttributeError( - f"Attribute {key} already exists. Use force=True to overwrite." - ) + if warn: + warnings.warn( + f"Attribute {key} already exists. Use force=True to overwrite." + ) + else: + raise AttributeError( + f"Attribute {key} already exists. Use force=True to overwrite." + ) return setattr(self, key, value) def __repr__(self):