Skip to content
This repository has been archived by the owner on Nov 3, 2023. It is now read-only.

[mutators] Prevent name collisions in mutators. #4006

Merged
merged 5 commits into from
Sep 22, 2021
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions parlai/core/mutators.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,11 @@ def register_mutator(name: str) -> Callable[[Type], Type]:

def _inner(cls_: Type) -> Type:
global MUTATOR_REGISTRY
if name in MUTATOR_REGISTRY and cls_ is not MUTATOR_REGISTRY[name]:
raise NameError(
"Mutators must be uniquely named, but detected two mutators with "
f"the name '{name}'."
)
MUTATOR_REGISTRY[name] = cls_
return cls_

Expand Down
23 changes: 23 additions & 0 deletions tests/test_mutators.py
Original file line number Diff line number Diff line change
Expand Up @@ -250,3 +250,26 @@ def test_not_sticky(self):
second_epoch.append(teacher.act())

assert all(f == s for f, s in zip(first_epoch, second_epoch))


class TestUniqueness(unittest.TestCase):
"""
Test that mutators cannot have duplicate names.
"""

def test_uniqueness(self):
from parlai.core.mutators import register_mutator, Mutator

@register_mutator("test_unique_mutator")
class Mutator1(Mutator):
pass

# don't freak out if we accidentally register the exact same class twice
register_mutator("test_unique_mutator")(Mutator1)

# but do demand uniqueness
with self.assertRaises(NameError):

@register_mutator("test_unique_mutator")
class Mutator2(Mutator):
pass