Skip to content

Commit

Permalink
refator(basic): EnumMeta
Browse files Browse the repository at this point in the history
自定义枚举的 __getitem__ 方法,使得通过字符串访问枚举成员时对大小写不敏感
  • Loading branch information
Snoopy1866 committed Sep 22, 2024
1 parent 19b56f0 commit 3ca0198
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
12 changes: 12 additions & 0 deletions src/pystatpower/basic.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from enum import Enum, EnumMeta
from math import ceil, floor, inf, isclose, trunc
from numbers import Real

Expand Down Expand Up @@ -92,6 +93,7 @@ def pseudo_bound(self, eps: Real = 1e-10) -> tuple[Real, Real]:


class PowerAnalysisNumeric(Real):
"""自定义功效分析数值类型"""

_domain = Interval(-inf, inf, lower_inclusive=True, upper_inclusive=True)

Expand Down Expand Up @@ -242,6 +244,16 @@ def __bool__(self):
return bool(self._value)


class PowerAnalysisOption(EnumMeta):
"""自定义功效分析选项的枚举元类,用于支持大小写不敏感的枚举值访问。"""

def __getitem__(self, name):
if isinstance(name, str):
return super().__getitem__(name.upper())
else:
return super().__getitem__(name)


class Alpha(PowerAnalysisNumeric):
"""显著性水平"""

Expand Down
17 changes: 17 additions & 0 deletions tests/test_basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -316,6 +316,23 @@ def test_bool(self):
assert bool(PowerAnalysisNumeric(-inf)) == bool(-inf)


class TestPowerAnalysisOption:
def test_getitem(self):
class TestEnum(Enum, metaclass=PowerAnalysisOption):
A = 1
B = 2

assert TestEnum["A"] == TestEnum.A
assert TestEnum["a"] == TestEnum.A
assert TestEnum["B"] == TestEnum.B
assert TestEnum["b"] == TestEnum.B

with pytest.raises(KeyError):
TestEnum["C"]
with pytest.raises(KeyError):
TestEnum[TestEnum.A]


def test_alpha():
assert Alpha(0.05) == 0.05

Expand Down

0 comments on commit 3ca0198

Please sign in to comment.