Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Feature] Allow register multi-name for a module simultaneously #775

Merged
merged 5 commits into from
Jan 7, 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
18 changes: 13 additions & 5 deletions mmcv/utils/registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import warnings
from functools import partial

from .misc import is_str
from .misc import is_seq_of, is_str


class Registry:
Expand Down Expand Up @@ -54,10 +54,18 @@ def _register_module(self, module_class, module_name=None, force=False):

if module_name is None:
module_name = module_class.__name__
if not force and module_name in self._module_dict:
raise KeyError(f'{module_name} is already registered '
f'in {self.name}')
self._module_dict[module_name] = module_class
if is_str(module_name):
ZwwWayne marked this conversation as resolved.
Show resolved Hide resolved
ZwwWayne marked this conversation as resolved.
Show resolved Hide resolved
module_name = [module_name]
else:
assert is_seq_of(
module_name,
str), ('module_name should be either of None, an '
f'instance of str or list, but got {type(module_name)}')
for name in module_name:
if not force and name in self._module_dict:
raise KeyError(f'{name} is already registered '
f'in {self.name}')
self._module_dict[name] = module_class

def deprecated_register_module(self, cls=None, force=False):
warnings.warn(
Expand Down
7 changes: 7 additions & 0 deletions tests/test_utils/test_registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,9 @@ class SphynxCat:
CATS.register_module(name='Sphynx', module=SphynxCat)
assert CATS.get('Sphynx') is SphynxCat

CATS.register_module(name=['Sphynx1', 'Sphynx2'], module=SphynxCat)
assert CATS.get('Sphynx2') is SphynxCat

repr_str = 'Registry(name=cat, items={'
repr_str += ("'BritishShorthair': <class 'test_registry.test_registry."
"<locals>.BritishShorthair'>, ")
Expand All @@ -70,6 +73,10 @@ class SphynxCat:
repr_str += '})'
assert repr(CATS) == repr_str

# name type
with pytest.raises(AssertionError):
CATS.register_module(name=7474741, module=SphynxCat)

# the registered module should be a class
with pytest.raises(TypeError):
CATS.register_module(0)
Expand Down