get initialized instance with config Parameters ---------- config : InstConf default_module : Python module Optional. It should be a python module. NOTE: the "module_path" will be override by `module` arguments This function will load class from the co
(
config: InstConf,
default_module=None,
accept_types: Union[type, Tuple[type]] = (),
try_kwargs: Dict = {},
**kwargs,
)
| 120 | |
| 121 | |
| 122 | def init_instance_by_config( |
| 123 | config: InstConf, |
| 124 | default_module=None, |
| 125 | accept_types: Union[type, Tuple[type]] = (), |
| 126 | try_kwargs: Dict = {}, |
| 127 | **kwargs, |
| 128 | ) -> Any: |
| 129 | """ |
| 130 | get initialized instance with config |
| 131 | |
| 132 | Parameters |
| 133 | ---------- |
| 134 | config : InstConf |
| 135 | |
| 136 | default_module : Python module |
| 137 | Optional. It should be a python module. |
| 138 | NOTE: the "module_path" will be override by `module` arguments |
| 139 | |
| 140 | This function will load class from the config['module_path'] first. |
| 141 | If config['module_path'] doesn't exists, it will load the class from default_module. |
| 142 | |
| 143 | accept_types: Union[type, Tuple[type]] |
| 144 | Optional. If the config is a instance of specific type, return the config directly. |
| 145 | This will be passed into the second parameter of isinstance. |
| 146 | |
| 147 | try_kwargs: Dict |
| 148 | Try to pass in kwargs in `try_kwargs` when initialized the instance |
| 149 | If error occurred, it will fail back to initialization without try_kwargs. |
| 150 | |
| 151 | Returns |
| 152 | ------- |
| 153 | object: |
| 154 | An initialized object based on the config info |
| 155 | """ |
| 156 | if isinstance(config, accept_types): |
| 157 | return config |
| 158 | |
| 159 | if isinstance(config, (str, Path)): |
| 160 | if isinstance(config, str): |
| 161 | # path like 'file:///<path to pickle file>/obj.pkl' |
| 162 | pr = urlparse(config) |
| 163 | if pr.scheme == "file": |
| 164 | |
| 165 | # To enable relative path like file://data/a/b/c.pkl. pr.netloc will be data |
| 166 | path = pr.path |
| 167 | if pr.netloc != "": |
| 168 | path = path.lstrip("/") |
| 169 | |
| 170 | pr_path = os.path.join(pr.netloc, path) if bool(pr.path) else pr.netloc |
| 171 | with open(os.path.normpath(pr_path), "rb") as f: |
| 172 | return pickle.load(f) |
| 173 | else: |
| 174 | with config.open("rb") as f: |
| 175 | return pickle.load(f) |
| 176 | |
| 177 | klass, cls_kwargs = get_callable_kwargs(config, default_module=default_module) |
| 178 | |
| 179 | try: |