|
31 | 31 | __doctest_skip__ = ["MetricCollection.plot", "MetricCollection.plot_all"] |
32 | 32 |
|
33 | 33 |
|
| 34 | +def _remove_prefix(string: str, prefix: str) -> str: |
| 35 | + """Patch for older version with missing method `removeprefix`. |
| 36 | +
|
| 37 | + >>> _remove_prefix("prefix_string", "prefix_") |
| 38 | + 'string' |
| 39 | + >>> _remove_prefix("not_prefix_string", "prefix_") |
| 40 | + 'not_prefix_string' |
| 41 | +
|
| 42 | + """ |
| 43 | + return string[len(prefix) :] if string.startswith(prefix) else string |
| 44 | + |
| 45 | + |
| 46 | +def _remove_suffix(string: str, suffix: str) -> str: |
| 47 | + """Patch for older version with missing method `removesuffix`. |
| 48 | +
|
| 49 | + >>> _remove_suffix("string_suffix", "_suffix") |
| 50 | + 'string' |
| 51 | + >>> _remove_suffix("string_suffix_missing", "_suffix") |
| 52 | + 'string_suffix_missing' |
| 53 | +
|
| 54 | + """ |
| 55 | + return string[: -len(suffix)] if string.endswith(suffix) else string |
| 56 | + |
| 57 | + |
34 | 58 | class MetricCollection(ModuleDict): |
35 | 59 | """MetricCollection class can be used to chain metrics that have the same call pattern into one single class. |
36 | 60 |
|
@@ -558,9 +582,9 @@ def __getitem__(self, key: str, copy_state: bool = True) -> Metric: |
558 | 582 | """ |
559 | 583 | self._compute_groups_create_state_ref(copy_state) |
560 | 584 | if self.prefix: |
561 | | - key = key.removeprefix(self.prefix) |
| 585 | + key = _remove_prefix(key, self.prefix) |
562 | 586 | if self.postfix: |
563 | | - key = key.removesuffix(self.postfix) |
| 587 | + key = _remove_suffix(key, self.postfix) |
564 | 588 | return self._modules[key] |
565 | 589 |
|
566 | 590 | @staticmethod |
|
0 commit comments