Function build


def build(self, external_args=None)


Instantiates target object connected to config class

Mentioned in


Lines 95-135 in anyfig/

def build(self, external_args=None):
  ''' Instantiates target object connected to config class '''
  if external_args is None:
    external_args = dict()
  config_name = type(self).__name__
  assert self._build_target is not None, f"Config class '{config_name}' isn't connected to a target"
  err_msg = f"Expected 'external_args' to be dict like object, was type '{type(external_args)}'"
  assert isinstance(external_args, Mapping), err_msg
  config_attrs = self.get_parameters()
  common_keys = set(config_attrs).intersection(set(external_args))
  err_msg = f"Arguments '{', '.join(common_keys)}' aren't allowed as they are already defined in '{config_name}'"
  assert common_keys == set(), err_msg
  build_args = {**external_args, **config_attrs}
  err_msg_base = f'when building {self._build_target} for config {config_name}'
  target = self._build_target
  # If target is a class and not implemented in C-code
  if inspect.isclass(target) and target.__init__ != object.__init__:
    target = target.__init__
  # Validate inspected arguments
    all_args, required_args = figutils.find_arguments(target)
    err_msg = f"Unexpected arguments {set(build_args) - set(all_args)} {err_msg_base}"
    assert set(build_args) <= set(all_args), err_msg
    err_msg = f"Missing required arguments {set(required_args) - set(build_args)} {err_msg_base}"
    assert set(required_args) <= set(build_args), err_msg
  # C-code (CPython) can't be inspected so arguments can't be validated
  except ValueError:
      return self._build_target(**build_args)
    except Exception as e:
      # Add to error message if instantiation didn't succeed
      raise type(e)(f"{e} {err_msg_base}") from None
  return self._build_target(**build_args)

Add Discussion as Guest

Log in