Skip to content

Commit 30cd82b

Browse files
kaushikcfdinducer
authored andcommitted
UniqueNameGenerator.add_name(s?): new argument existing_ok
1 parent 81718ff commit 30cd82b

File tree

2 files changed

+27
-4
lines changed

2 files changed

+27
-4
lines changed

pytools/__init__.py

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2311,8 +2311,14 @@ def _name_added(self, name: str) -> None:
23112311
"""
23122312
pass
23132313

2314-
def add_name(self, name: str) -> None:
2315-
if self.is_name_conflicting(name):
2314+
def add_name(self, name: str, *, conflicting_ok: bool = False) -> None:
2315+
"""
2316+
:arg conflicting_ok: A flag to dictate the behavior when *name* is
2317+
conflicting with the set of existing names. If *True*, a conflict
2318+
is silently passed. If *False*, a :class:`ValueError` is raised on
2319+
encountering a conflict.
2320+
"""
2321+
if (not conflicting_ok) and self.is_name_conflicting(name):
23162322
raise ValueError(f"name '{name}' conflicts with existing names")
23172323

23182324
if not name.startswith(self.forced_prefix):
@@ -2323,9 +2329,14 @@ def add_name(self, name: str) -> None:
23232329
self.existing_names.add(name)
23242330
self._name_added(name)
23252331

2326-
def add_names(self, names: Iterable[str]) -> None:
2332+
def add_names(self, names: Iterable[str],
2333+
*,
2334+
conflicting_ok: bool = False) -> None:
2335+
"""
2336+
:arg conflicting_ok: Plainly passed to :meth:`UniqueNameGenerator.add_name`.
2337+
"""
23272338
for name in names:
2328-
self.add_name(name)
2339+
self.add_name(name, conflicting_ok=conflicting_ok)
23292340

23302341
def __call__(self, based_on: str = "id") -> str:
23312342
based_on = self.forced_prefix + based_on

test/test_pytools.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -652,6 +652,18 @@ def test_sphere_sampling(sampling, visualize=False):
652652
# }}}
653653

654654

655+
def test_unique_name_gen_conflicting_ok():
656+
from pytools import UniqueNameGenerator
657+
658+
ung = UniqueNameGenerator()
659+
ung.add_names({"a", "b", "c"})
660+
661+
with pytest.raises(ValueError):
662+
ung.add_names({"a"})
663+
664+
ung.add_names({"a", "b", "c"}, conflicting_ok=True)
665+
666+
655667
if __name__ == "__main__":
656668
if len(sys.argv) > 1:
657669
exec(sys.argv[1])

0 commit comments

Comments
 (0)