Skip to content

Commit 81711d2

Browse files
Avoid naming conflicts when importing multiple types with the same name from an ancestor package
1 parent e3135ce commit 81711d2

File tree

2 files changed

+9
-7
lines changed

2 files changed

+9
-7
lines changed

betterproto/compile/importing.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -121,18 +121,20 @@ def reference_ancestor(
121121
"""
122122
Returns a reference to a python type in a package which is an ancestor to the current package,
123123
and adds the required import that is aliased (if possible) to avoid name conflicts.
124+
125+
Adds trailing __ to avoid name mangling (python.org/dev/peps/pep-0008/#id34).
124126
"""
125127
distance_up = len(current_package) - len(py_package)
126128
if py_package:
127129
string_import = py_package[-1]
128-
# Add trailing __ to avoid name mangling (python.org/dev/peps/pep-0008/#id34)
129130
string_alias = f"_{'_' * distance_up}{string_import}__"
130131
string_from = f"..{'.' * distance_up}"
131132
imports.add(f"from {string_from} import {string_import} as {string_alias}")
132133
return f"{string_alias}.{py_type}"
133134
else:
134-
imports.add(f"from .{'.' * distance_up} import {py_type}")
135-
return py_type
135+
string_alias = f"{'_' * distance_up}{py_type}__"
136+
imports.add(f"from .{'.' * distance_up} import {py_type} as {string_alias}")
137+
return string_alias
136138

137139

138140
def reference_cousin(

betterproto/tests/test_get_ref_type.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -214,8 +214,8 @@ def test_reference_root_package_from_child():
214214
package="package.child", imports=imports, source_type="Message"
215215
)
216216

217-
assert imports == {"from ... import Message"}
218-
assert name == "Message"
217+
assert imports == {"from ... import Message as __Message__"}
218+
assert name == "__Message__"
219219

220220

221221
def test_reference_root_package_from_deeply_nested_child():
@@ -224,8 +224,8 @@ def test_reference_root_package_from_deeply_nested_child():
224224
package="package.deeply.nested.child", imports=imports, source_type="Message"
225225
)
226226

227-
assert imports == {"from ..... import Message"}
228-
assert name == "Message"
227+
assert imports == {"from ..... import Message as ____Message__"}
228+
assert name == "____Message__"
229229

230230

231231
def test_reference_unrelated_package():

0 commit comments

Comments
 (0)