Create an instance of given module class. Args: cls_or_name (type or str): Class of which to create instance. Returns: instance of type `cls_or_name`
(cls_or_name, **kwargs)
| 208 | |
| 209 | |
| 210 | def create(cls_or_name, **kwargs): |
| 211 | """ |
| 212 | Create an instance of given module class. |
| 213 | |
| 214 | Args: |
| 215 | cls_or_name (type or str): Class of which to create instance. |
| 216 | |
| 217 | Returns: instance of type `cls_or_name` |
| 218 | """ |
| 219 | assert type(cls_or_name) in [type, str |
| 220 | ], "should be a class or name of a class" |
| 221 | name = type(cls_or_name) == str and cls_or_name or cls_or_name.__name__ |
| 222 | if name in global_config: |
| 223 | if isinstance(global_config[name], SchemaDict): |
| 224 | pass |
| 225 | elif hasattr(global_config[name], "__dict__"): |
| 226 | # support instance return directly |
| 227 | return global_config[name] |
| 228 | else: |
| 229 | raise ValueError("The module {} is not registered".format(name)) |
| 230 | else: |
| 231 | raise ValueError("The module {} is not registered".format(name)) |
| 232 | |
| 233 | config = global_config[name] |
| 234 | cls = getattr(config.pymodule, name) |
| 235 | cls_kwargs = {} |
| 236 | cls_kwargs.update(global_config[name]) |
| 237 | |
| 238 | # parse `shared` annoation of registered modules |
| 239 | if getattr(config, 'shared', None): |
| 240 | for k in config.shared: |
| 241 | target_key = config[k] |
| 242 | shared_conf = config.schema[k].default |
| 243 | assert isinstance(shared_conf, SharedConfig) |
| 244 | if target_key is not None and not isinstance(target_key, |
| 245 | SharedConfig): |
| 246 | continue # value is given for the module |
| 247 | elif shared_conf.key in global_config: |
| 248 | # `key` is present in config |
| 249 | cls_kwargs[k] = global_config[shared_conf.key] |
| 250 | else: |
| 251 | cls_kwargs[k] = shared_conf.default_value |
| 252 | |
| 253 | # parse `inject` annoation of registered modules |
| 254 | if getattr(cls, 'from_config', None): |
| 255 | cls_kwargs.update(cls.from_config(config, **kwargs)) |
| 256 | |
| 257 | if getattr(config, 'inject', None): |
| 258 | for k in config.inject: |
| 259 | target_key = config[k] |
| 260 | # optional dependency |
| 261 | if target_key is None: |
| 262 | continue |
| 263 | |
| 264 | if isinstance(target_key, dict) or hasattr(target_key, '__dict__'): |
| 265 | if 'name' not in target_key.keys(): |
| 266 | continue |
| 267 | inject_name = str(target_key['name']) |