6
6
7
7
import dataclasses
8
8
import functools
9
+ from collections .abc import Mapping
9
10
from pathlib import Path
10
- from typing import Any , TypedDict
11
+ from typing import Any , TypedDict , Literal
11
12
12
13
import uproot
13
14
import uproot .reading
@@ -41,18 +42,40 @@ class MetaDict(MetaDictRequired, total=False):
41
42
guide_style : str
42
43
43
44
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
+
44
71
@dataclasses .dataclass
45
72
class UprootEntry :
46
73
path : str
47
74
item : Any
48
75
49
76
@property
50
77
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 )
56
79
57
80
def meta (self ) -> MetaDict :
58
81
return process_item (self .item )
@@ -71,18 +94,10 @@ def tree_args(self) -> dict[str, Any]:
71
94
def children (self ) -> list [UprootEntry ]:
72
95
if not self .is_dir :
73
96
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
+
84
98
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 ))
86
101
]
87
102
88
103
0 commit comments