Safemotion Lib
Loading...
Searching...
No Matches
registry.py
Go to the documentation of this file.
1#!/usr/bin/env python3
2# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
3
4from typing import Dict, Optional
5
6
7class Registry(object):
8 """
9 The registry that provides name -> object mapping, to support third-party
10 users' custom modules.
11 To create a registry (e.g. a backbone registry):
12 .. code-block:: python
13 BACKBONE_REGISTRY = Registry('BACKBONE')
14 To register an object:
15 .. code-block:: python
16 @BACKBONE_REGISTRY.register()
17 class MyBackbone():
18 ...
19 Or:
20 .. code-block:: python
21 BACKBONE_REGISTRY.register(MyBackbone)
22 """
23
24 def __init__(self, name: str) -> None:
25 """
26 Args:
27 name (str): the name of this registry
28 """
29 self._name: str = name
30 self._obj_map: Dict[str, object] = {}
31
32 def _do_register(self, name: str, obj: object) -> None:
33 assert (
34 name not in self._obj_map
35 ), "An object named '{}' was already registered in '{}' registry!".format(
36 name, self._name
37 )
38 self._obj_map[name] = obj
39
40 def register(self, obj: object = None) -> Optional[object]:
41 """
42 Register the given object under the the name `obj.__name__`.
43 Can be used as either a decorator or not. See docstring of this class for usage.
44 """
45 if obj is None:
46 # used as a decorator
47 def deco(func_or_class: object) -> object:
48 name = func_or_class.__name__ # pyre-ignore
49 self._do_register(name, func_or_class)
50 return func_or_class
51
52 return deco
53
54 # used as a function call
55 name = obj.__name__ # pyre-ignore
56 self._do_register(name, obj)
57
58 def get(self, name: str) -> object:
59 ret = self._obj_map.get(name)
60 if ret is None:
61 raise KeyError(
62 "No object named '{}' found in '{}' registry!".format(
63 name, self._name
64 )
65 )
66 return ret
object get(self, str name)
Definition registry.py:58
None _do_register(self, str name, object obj)
Definition registry.py:32
Optional[object] register(self, object obj=None)
Definition registry.py:40
None __init__(self, str name)
Definition registry.py:24