Skip to content

Commit

Permalink
refactor: Simplify decorators to labels function
Browse files Browse the repository at this point in the history
  • Loading branch information
pawamoy committed Apr 22, 2022
1 parent bd2504b commit 04e768f
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 19 deletions.
24 changes: 9 additions & 15 deletions src/griffe/agents/visitor.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,16 +48,16 @@
from griffe.expressions import Expression, Name

builtin_decorators = {
"property",
"staticmethod",
"classmethod",
"property": "property",
"staticmethod": "staticmethod",
"classmethod": "classmethod",
}

stdlib_decorators = {
"abc.abstractmethod",
"functools.cache",
"functools.cached_property",
"functools.lru_cache",
"abc.abstractmethod": {"abstractmethod"},
"functools.cache": {"cached"},
"functools.cached_property": {"cached", "property"},
"functools.lru_cache": {"cached"},
}


Expand Down Expand Up @@ -268,20 +268,14 @@ def decorators_to_labels(self, decorators: list[Decorator]) -> set[str]: # noqa
for decorator in decorators:
decorator_value = decorator.value.split("(", 1)[0]
if decorator_value in builtin_decorators:
labels.add(decorator_value)
labels.add(builtin_decorators[decorator_value])
else:
names = decorator_value.split(".")
with suppress(NameResolutionError):
resolved_first = self.current.resolve(names[0])
resolved_name = ".".join([resolved_first, *names[1:]])
if resolved_name in stdlib_decorators:
if "abstractmethod" in resolved_name:
labels.add("abstractmethod")
elif "cached_property" in resolved_name:
labels.add("cached")
labels.add("property")
elif "cache" in resolved_name:
labels.add("cached")
labels |= stdlib_decorators[resolved_name]
return labels

def get_base_property(self, decorators: list[Decorator]) -> tuple[Function | None, str | None]:
Expand Down
8 changes: 4 additions & 4 deletions tests/test_visitor.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,19 +108,19 @@ def test_not_defined_at_runtime():
("staticmethod", {"staticmethod"}),
("classmethod", {"classmethod"}),
("functools.cache", {"cached"}),
("cache", {"cached"}),
("functools.cached_property", {"cached", "property"}),
("cached_property", {"cached", "property"}),
("functools.lru_cache", {"cached"}),
("functools.lru_cache(maxsize=8)", {"cached"}),
("cache", {"cached"}),
("cached_property", {"cached", "property"}),
("lru_cache", {"cached"}),
("lru_cache(maxsize=8)", {"cached"}),
("abc.abstractmethod", {"abstractmethod"}),
("abstractmethod", {"abstractmethod"}),
],
)
def test_set_labels_using_decorators(decorator, labels):
"""Assert decorators are used to set labels on objects.
def test_set_function_labels_using_decorators(decorator, labels):
"""Assert decorators are used to set labels on functions.
Parameters:
decorator: A parametrized decorator.
Expand Down

0 comments on commit 04e768f

Please sign in to comment.