Skip to content

Commit

Permalink
Fix AttrFormatter - rewrite with clearer code
Browse files Browse the repository at this point in the history
  • Loading branch information
aulemahal committed Oct 16, 2023
1 parent a935e66 commit 3c3ac9a
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 11 deletions.
2 changes: 1 addition & 1 deletion tests/test_indicators.py
Original file line number Diff line number Diff line change
Expand Up @@ -592,7 +592,7 @@ def test_AttrFormatter():
# Missing mod:
assert fmt.format("{adj}", adj="evil") == "méchant"
# Mod with unknown value
with pytest.raises(ValueError):
with pytest.warns(match="Requested formatting `m` for unknown string `funny`."):
fmt.format("{adj:m}", adj="funny")


Expand Down
34 changes: 24 additions & 10 deletions xclim/core/formatting.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@

import datetime as dt
import itertools
import logging
import re
import string
import warnings
from ast import literal_eval
from fnmatch import fnmatch
from inspect import _empty, signature # noqa
Expand Down Expand Up @@ -124,18 +124,30 @@ def format_field(self, value, format_spec):
'La moyenne annuelle est faite sur un échantillon mensuel'
"""
baseval = self._match_value(value)
if baseval is not None and not format_spec:
if baseval is None: # Not something we know how to translate
if format_spec in self.modifiers + [
"r"
]: # Woops, however a known format spec was asked
warnings.warn(
f"Requested formatting `{format_spec}` for unknown string `{value}`."
)
format_spec = ""
return super().format_field(value, format_spec)
# Thus, known value

if not format_spec: # (None or '') No modifiers, return first
return self.mapping[baseval][0]

if format_spec in self.modifiers:
if baseval is not None:
return self.mapping[baseval][self.modifiers.index(format_spec)]
raise ValueError(
f"No known mapping for string '{value}' with modifier '{format_spec}'"
)
if format_spec == "r":
if format_spec == "r": # Raw modifier
return super().format_field(value, "")
return super().format_field(value, format_spec)

if format_spec in self.modifiers: # Known modifier
if len(self.mapping[baseval]) == 1: # But unmodifiable entry
return self.mapping[baseval][0]
# Known modifier, modifiable entry
return self.mapping[baseval][self.modifiers.index(format_spec)]
# Known value but unknown modifier, must be a built-in one, only works for the default val...
return super().format_field(self.mapping[baseval][0], format_spec)

def _match_value(self, value):
if isinstance(value, str):
Expand Down Expand Up @@ -181,6 +193,8 @@ def _match_value(self, value):
"var": ["variance"],
"absamp": ["absolute amplitude"],
"relamp": ["relative amplitude"],
# For when we are formatting indicator classes with empty options
"<class 'inspect._empty'>": ["<empty>"],
},
["adj", "noun"],
)
Expand Down

0 comments on commit 3c3ac9a

Please sign in to comment.