Skip to content

Commit fdb21d9

Browse files
committed
feat: Add properties telling whether an expression name resolves to an enumeration class, instance or value
Issue-mkdocstrings/python#124: mkdocstrings/python#124
1 parent 01da648 commit fdb21d9

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

enumvalues.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
from griffe.dataclasses import Object
2+
from griffe.expressions import ExprName
3+
from griffe.tests import temporary_visited_module
4+
5+
6+
with temporary_visited_module(
7+
"""
8+
from enum import Enum
9+
10+
class MyEnum(Enum):
11+
MY_FIELD = "hello"
12+
13+
my_fields = [MyEnum.MY_FIELD.value]
14+
""",
15+
) as module:
16+
expression = module["my_fields"].value
17+
18+
19+
attribute = expression.elements[0]
20+
print(attribute.last.parent.is_enum_value)

src/griffe/expressions.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -607,6 +607,33 @@ def canonical_path(self) -> str:
607607
except NameResolutionError:
608608
return self.name
609609

610+
@property
611+
def is_enum_class(self) -> bool:
612+
"""Whether this name resolves to an enumeration class."""
613+
try:
614+
bases = self.parent[self.name].bases # type: ignore[union-attr,index]
615+
except Exception: # noqa: BLE001
616+
return False
617+
618+
# TODO: Support inheritance?
619+
return any(isinstance(base, Expr) and base.canonical_path == "enum.Enum" for base in bases)
620+
621+
@property
622+
def is_enum_instance(self) -> bool:
623+
"""Whether this name resolves to an enumeration instance."""
624+
try:
625+
return self.parent.is_enum_class # type: ignore[union-attr]
626+
except Exception: # noqa: BLE001
627+
return False
628+
629+
@property
630+
def is_enum_value(self) -> bool:
631+
"""Whether this name resolves to an enumeration value."""
632+
try:
633+
return self.name == "value" and self.parent.is_enum_instance # type: ignore[union-attr]
634+
except Exception: # noqa: BLE001
635+
return False
636+
610637

611638
@dataclass(eq=True, **dataclass_opts)
612639
class ExprNamedExpr(Expr):

0 commit comments

Comments
 (0)