Skip to content

Commit

Permalink
Add tier attribute as named attribute for VariableCode
Browse files Browse the repository at this point in the history
  • Loading branch information
dc-almeida committed Oct 29, 2024
1 parent 7913ff1 commit 41ff25b
Showing 1 changed file with 16 additions and 1 deletion.
17 changes: 16 additions & 1 deletion nomenclature/code.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,12 +125,26 @@ def replace_tag(self, tag: str, target: "Code") -> "Code":
def _replace_or_recurse(_attr, _value):
# if the attribute is a string and contains "{tag}" replace
if isinstance(_value, str) and "{" + tag + "}" in _value:
# if the the target has the corresponding attribute replace
# if the target has the corresponding attribute replace
if _attr in target.flattened_dict:
return _value.replace("{" + tag + "}", getattr(target, _attr))
# otherwise return the name
else:
return _value.replace("{" + tag + "}", getattr(target, "name"))
# if the attribute is an integer and "tier"
elif isinstance(_value, int) and _attr == "tier":
# if tier in tag is str formatted as "^1"/"^2"
if (tag_tier := getattr(target, _attr, None)) in {"^1", "^2"}:
return _value + int(tag_tier[-1])
# if tag doesn't have tier attribute
elif not tag_tier:
return _value
# else misformatted tier in tag
else:
raise ValueError(
f"Tag '{target.name}' includes misformatted 'tier' attribute. "
"Allowed values for tier attributes in tags are '^1' or '^2'."
)
# if the attribute is a list, iterate over the items and replace tags
elif isinstance(_value, list):
return [_replace_or_recurse(_attr, _v) for _v in _value]
Expand Down Expand Up @@ -164,6 +178,7 @@ def __setattr__(self, name, value):

class VariableCode(Code):
unit: Union[str, List[str]] = Field(...)
tier: int | None = None
weight: str | None = None
region_aggregation: List[Dict[str, Dict]] | None = Field(
default=None, alias="region-aggregation"
Expand Down

0 comments on commit 41ff25b

Please sign in to comment.