panoptes / POCS

An Observatory Control System for the PANOPTES citizen-science project designed to help find transiting exoplanets! :telescope: :stars:
https://pocs.readthedocs.io/en/latest/
MIT License
80 stars 49 forks source link

Consider adding `from_config` as a classmethod in `PanBase` #1142

Open danjampro opened 3 years ago

danjampro commented 3 years ago

Class initialisation is currently done using a mixture of kwargs, calls to get_config inside __init__, as well as a variety of factory functions such as create_xxx_from_config. We can partially improve this by standardising how classes are intialised from config by adding a new classmethod similar to this:

    @classmethod
    def from_config(cls, config=None, logger=None, **kwargs):
        """
        """
        config_name = cls.__name__ if cls._config_name is None else cls._config_name
        config = get_config() if config is None else config
        logger = get_logger() if logger is None else logger
        instance_kwargs = config.get(config_name, {})
        instance_kwargs.update(**kwargs)
        logger.debug(f"Creating {cls.__name__} instance with kwargs: {instance_kwargs}")
        return cls(config=config, logger=logger, **instance_kwargs)

Configured class instances can then be created like this: instance = Class.from_config()

This would allow us to remove calls to get_config() inside classes where possible (except for config items that need to be kept dynamic) as well as removing all the create_xxx_from_config functions.