nono
nono

Reputation: 185

Building a "Catalogue" mapping configurations to classes in python

I have many classes in Python, all inherited from the same abstract class. Each class has a config of its own. I want to create a catalog/builder class where I map the configs to the classes once. The catalog can then be used to

  1. List the different configs registered to it, and have them autocomplete in standard IDEs
  2. Allow me to define the configs
  3. Instantiate the suiting object from the config

Example:

@dataclass
class AConfig(MyAbstractConfig):
    a: int = 1

class A(MyAbstractClass):
    def __init__(config: AConfig):
        self.a = config.a

@dataclass
class BConfig(MyAbstractConfig):
    b: int = 1

class B(MyAbstractClass):
    def __init__(config: BConfig):
        self.b = config.b


# This is just an example interface, the important thing is to define the items in the catalog once 
class MyCatalog(Catalog):
    AConfig = A
    BConfig = B

print(MyCatalog.AConfig(a=1).build()  # A(1)

MyCatalog.BCo  # This would autocomplete to MyCatalog.BConfig in standard IDEs

I currently have a class containing only part of these features:

class Catalog:

    def __init__():
        catalog = {}

    def register(config_type: Type[MyAbstractConfig], obj: Type[MyAbstractClass]):
        catalog[config] = obj

    def build(config: MyAbstractConfig) -> MyAbstractClass:
        obj = self.catalog[type(config)]
        return obj(config)


Catalog.register(AConfig, A)
Catalog.register(BConfig, B)

a_config = AConfig(a=1)
Catalog.build(a_config)  # A(1)

This does not list all the options, so I need to know exactly which config I would like to import and use.

Upvotes: 0

Views: 22

Answers (0)

Related Questions