Function config_class

Synopsis

def config_class(cls=None, *target=None)

Description

Adds Anyfig functionality to the class and registers it to known config classes

Mentioned in

Source

Lines 176-222 in anyfig/anyfig_setup.py.

def config_class(cls=None, *, target=None):
  ''' Adds Anyfig functionality to the class and registers it to known config classes '''
  def wrap(cls):
    class_name = cls.__name__

    # Makes sure that nothing fishy is going on...
    err_msg = f"Can't decorate '{class_name}' of type {type(cls)}. Can only be used for classes"
    assert inspect.isclass(cls), err_msg
    if target is not None:
      err_msg = f"Expected target to be callable, was {type(target)}"
      assert callable(target), err_msg

    # Config class methods
    functions = inspect.getmembers(cls, inspect.isfunction)
    functions = {name: function for name, function in functions}

    # Transfers functions from MasterConfig to config class
    for name, function in inspect.getmembers(MasterConfig, inspect.isfunction):
      if name not in functions:  # Only transfer not implemented functions
        setattr(cls, name, function)

    # Wrap init function to add attributes
    def init_wrapper(func):
      default_attributes = figutils.default_config_attributes()

      @wraps(func)
      def wrapper(*args, **kwargs):
        self = args[0]
        self._frozen = default_attributes['_frozen']
        self._build_target = target if target else default_attributes[
          '_build_target']
        func(*args, **kwargs)

      return wrapper

    cls.__init__ = init_wrapper(cls.__init__)

    figutils.register_config_class(class_name, cls)
    return dataclass(cls)

  # Called as @config_class() or @config_class(target=...).
  if cls is None or target is not None:
    return wrap

  # Called as @config_class without parentheses
  return wrap(dataclass(cls))





Add Discussion as Guest

Log in