Skip to content

Commit

Permalink
RFC: reduce code complexity in find_lowest_subclasses helper function
Browse files Browse the repository at this point in the history
  • Loading branch information
yut23 committed Apr 12, 2023
1 parent c29aae4 commit 15487c0
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 19 deletions.
21 changes: 3 additions & 18 deletions yt/utilities/hierarchy_inspection.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import inspect
from collections import Counter
from functools import reduce
from typing import List, Type

from more_itertools import flatten


def find_lowest_subclasses(candidates: List[Type]) -> List[Type]:
"""
Expand All @@ -22,21 +23,5 @@ def find_lowest_subclasses(candidates: List[Type]) -> List[Type]:
A list of classes which are not super classes for any others in
candidates.
"""

# If there is only one input, the input candidate is always the
# lowest class
if len(candidates) == 1:
return candidates
elif len(candidates) == 0:
return []

mros = [inspect.getmro(c) for c in candidates]

counters = [Counter(mro) for mro in mros]

if len(counters) == 0:
return []

count = reduce(lambda x, y: x + y, counters)

count = Counter(flatten(inspect.getmro(c) for c in candidates))
return [x for x in candidates if count[x] == 1]
13 changes: 12 additions & 1 deletion yt/utilities/tests/test_hierarchy_inspection.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,11 @@ class level4(level3):
pass


def test_empty():
result = find_lowest_subclasses([])
assert len(result) == 0


def test_single():
result = find_lowest_subclasses([level2])
assert len(result) == 1
Expand Down Expand Up @@ -60,4 +65,10 @@ def test_diverging_tree():
def test_without_parents():
result = find_lowest_subclasses([level1, level3])
assert len(result) == 1
assert level3 in result
assert result[0] is level3


def test_without_grandparents():
result = find_lowest_subclasses([level1, level4])
assert len(result) == 1
assert result[0] is level4

0 comments on commit 15487c0

Please sign in to comment.