Skip to content

Commit

Permalink
feat: warn if set method is used on rules instead of directly failing
Browse files Browse the repository at this point in the history
  • Loading branch information
pgierz committed Oct 7, 2024
1 parent 7060517 commit f828fd8
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 7 deletions.
4 changes: 2 additions & 2 deletions doc/pymorize_building_blocks.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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``.

19 changes: 14 additions & 5 deletions src/pymorize/rule.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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
-------
Expand All @@ -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):
Expand Down

0 comments on commit f828fd8

Please sign in to comment.