Skip to content

Commit e1301fa

Browse files
committed
refactor: more singledispatch
Signed-off-by: Henry Schreiner <[email protected]>
1 parent 0555350 commit e1301fa

File tree

1 file changed

+32
-17
lines changed

1 file changed

+32
-17
lines changed

src/uproot_browser/tree.py

Lines changed: 32 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,9 @@
66

77
import dataclasses
88
import functools
9+
from collections.abc import Mapping
910
from pathlib import Path
10-
from typing import Any, TypedDict
11+
from typing import Any, TypedDict, Literal
1112

1213
import uproot
1314
import uproot.reading
@@ -41,18 +42,40 @@ class MetaDict(MetaDictRequired, total=False):
4142
guide_style: str
4243

4344

45+
@functools.singledispatch
46+
def is_dir(item: Any) -> bool:
47+
return False
48+
49+
@is_dir.register
50+
def _(item: uproot.reading.ReadOnlyDirectory) -> Literal[True]:
51+
return True
52+
53+
@is_dir.register
54+
def _(item: uproot.behaviors.TBranch.HasBranches) -> bool:
55+
return len(item.branches) > 0
56+
57+
58+
@functools.singledispatch
59+
def get_children(item: Any) -> set[str]:
60+
raise RuntimeError("Should not be called, protect with is_dir!")
61+
62+
@get_children.register
63+
def _(item: Mapping) -> set[str]:
64+
return {
65+
key.split(";")[0]
66+
for key in item.keys() # noqa: SIM118
67+
if "/" not in key
68+
}
69+
70+
4471
@dataclasses.dataclass
4572
class UprootEntry:
4673
path: str
4774
item: Any
4875

4976
@property
5077
def is_dir(self) -> bool:
51-
if isinstance(self.item, uproot.reading.ReadOnlyDirectory):
52-
return True
53-
if isinstance(self.item, uproot.behaviors.TBranch.HasBranches):
54-
return len(self.item.branches) > 0
55-
return False
78+
return is_dir(self.item)
5679

5780
def meta(self) -> MetaDict:
5881
return process_item(self.item)
@@ -71,18 +94,10 @@ def tree_args(self) -> dict[str, Any]:
7194
def children(self) -> list[UprootEntry]:
7295
if not self.is_dir:
7396
return []
74-
if isinstance(self.item, uproot.reading.ReadOnlyDirectory):
75-
items = {
76-
key.split(";")[0]
77-
for key in self.item.keys() # noqa: SIM118
78-
if "/" not in key
79-
}
80-
elif isinstance(self.item, uproot.behaviors.TBranch.HasBranches):
81-
items = {item.name for item in self.item.branches}
82-
else:
83-
items = {obj.name.split(";")[0] for obj in self.item.branches}
97+
8498
return [
85-
UprootEntry(f"{self.path}/{key}", self.item[key]) for key in sorted(items)
99+
UprootEntry(f"{self.path}/{key}", self.item[key])
100+
for key in sorted(get_children(self.item))
86101
]
87102

88103

0 commit comments

Comments
 (0)