Skip to content

Commit

Permalink
feat: Add properties telling whether an expression name resolves to a…
Browse files Browse the repository at this point in the history
…n enumeration class, instance or value

Issue-mkdocstrings/python#124: mkdocstrings/python#124
  • Loading branch information
pawamoy committed Apr 18, 2024
1 parent 01da648 commit fdb21d9
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
20 changes: 20 additions & 0 deletions enumvalues.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
from griffe.dataclasses import Object
from griffe.expressions import ExprName
from griffe.tests import temporary_visited_module


with temporary_visited_module(
"""
from enum import Enum
class MyEnum(Enum):
MY_FIELD = "hello"
my_fields = [MyEnum.MY_FIELD.value]
""",
) as module:
expression = module["my_fields"].value


attribute = expression.elements[0]
print(attribute.last.parent.is_enum_value)
27 changes: 27 additions & 0 deletions src/griffe/expressions.py
Original file line number Diff line number Diff line change
Expand Up @@ -607,6 +607,33 @@ def canonical_path(self) -> str:
except NameResolutionError:
return self.name

@property
def is_enum_class(self) -> bool:
"""Whether this name resolves to an enumeration class."""
try:
bases = self.parent[self.name].bases # type: ignore[union-attr,index]
except Exception: # noqa: BLE001
return False

# TODO: Support inheritance?
return any(isinstance(base, Expr) and base.canonical_path == "enum.Enum" for base in bases)

@property
def is_enum_instance(self) -> bool:
"""Whether this name resolves to an enumeration instance."""
try:
return self.parent.is_enum_class # type: ignore[union-attr]
except Exception: # noqa: BLE001
return False

@property
def is_enum_value(self) -> bool:
"""Whether this name resolves to an enumeration value."""
try:
return self.name == "value" and self.parent.is_enum_instance # type: ignore[union-attr]
except Exception: # noqa: BLE001
return False


@dataclass(eq=True, **dataclass_opts)
class ExprNamedExpr(Expr):
Expand Down

0 comments on commit fdb21d9

Please sign in to comment.