Skip to content

Commit e6c86c9

Browse files
committed
Depth-first determination of abs name
1 parent c9ec2f8 commit e6c86c9

File tree

1 file changed

+12
-6
lines changed

1 file changed

+12
-6
lines changed

nn/base.py

+12-6
Original file line numberDiff line numberDiff line change
@@ -1215,12 +1215,14 @@ def _get_abs_canonical_name(self, join_str="/") -> str:
12151215
assert root_maker, f"root name ctx {self.root} is not assigned to a maker (module)"
12161216
if root_maker is self.maker:
12171217
return "" # special case
1218-
# Do a breadth-first search through the parents, starting from self.maker, until we find root_maker.
1218+
# Do a depth-first search through the parents, starting from self.maker, until we find root_maker.
1219+
# Use depth-first instead of breadth-first to prefer the first parent when there are multiple.
12191220
queue = [self.maker]
12201221
cache = {} # maker -> full name
12211222
while queue:
1222-
maker = queue.pop(0)
1223+
maker = queue.pop(-1) # depth-first
12231224
postfix = (join_str + cache[maker]) if maker in cache else ""
1225+
queue_ext = []
12241226
for parent, attr in maker.parents_with_attr():
12251227
if parent in cache:
12261228
continue
@@ -1232,7 +1234,8 @@ def _get_abs_canonical_name(self, join_str="/") -> str:
12321234
assert call.layer_abs_name_scope
12331235
return call.layer_abs_name_scope + join_str + attr + postfix
12341236
cache[parent] = attr + postfix
1235-
queue.append(parent)
1237+
queue_ext.append(parent)
1238+
queue.extend(reversed(queue_ext))
12361239
if root_maker in cache:
12371240
break
12381241
if root_maker not in cache:
@@ -1316,20 +1319,23 @@ def _get_suggested_name(self) -> str:
13161319
reserved_names = set(self.parent.children.keys()) | self._ReservedNames
13171320
if self.parent.maker:
13181321
# Check parent name scope maker, any attrib from there to self.maker.
1319-
# Do a breadth-first search through the parents, starting from self.maker,
1322+
# Do a depth-first search through the parents, starting from self.maker,
13201323
# until we find self.parent.maker.
1324+
# Somewhat consistent to _get_abs_canonical_name.
13211325
queue = [self.maker]
13221326
cache = {} # parent -> full attrib
13231327
while queue:
1324-
maker = queue.pop(0)
1328+
maker = queue.pop(-1) # depth-first
13251329
postfix = f".{cache[maker]}" if maker in cache else ""
1330+
queue_ext = []
13261331
for parent, attr in maker.parents_with_attr():
13271332
if parent in cache:
13281333
if cache[parent] in reserved_names:
13291334
cache[parent] = attr + postfix # anyway overwrite
13301335
continue
13311336
cache[parent] = attr + postfix
1332-
queue.append(parent)
1337+
queue_ext.append(parent)
1338+
queue.extend(reversed(queue_ext))
13331339
if self.parent.maker in cache:
13341340
break
13351341
if self.parent.maker in cache:

0 commit comments

Comments
 (0)