Home > Back-end >  In Python, how can I add another module to an already existing variable that contains one?
In Python, how can I add another module to an already existing variable that contains one?

Time:09-08

Is it possible use a variable as a container for a Python module, and then adding another one to the same variable?

So for example, if I would have a Python file called general_config.py containing a general config of some kind:

class GeneralConfig:
    attribute1 = "Some attribute"
    attribute2 = "Some other attribute"

And if I would import this Python module as a variable containing a general config, I would do:

import general_config.py as Config

Then I can access its attributes by doing:

generalParameter = Config.GeneralConfig.attribute1

But what if I want to add some specific parameters to my config (say from specific_config.py), while keeping the general one as part of the entire config? So it would do something like that:

if someSpecificCondition:
    Config  = import specific_config.py
else:
    Config  = import other_config.py

While keeping the Config in the original scope? Thanks in advance.

CodePudding user response:

Why not do:

if someSpecificCondition:
    from specific_config import SpecificConfig
    Config.SpecificConfig = SpecificConfig
else:
    from other_config import OtherConfig
    Config.OtherConfig = OtherConfig

But FYI this looks like you are using a singleton config pattern. If this was me, I would initialise the main config class once at the start of the program and pass down any required sub configs when required.

CodePudding user response:

If you want your general config to inherit your other configs for whatever reason, you could do something like this. But Tom's answer makes more sense, since there's no runtime class creation.

class Config:
    att = "hello world"


def inherit_configs(some_condition):
    if some_condition:
        from config1 import Config1

        class Config(Config, Config1):
            pass

        return Config
    else:
        from config2 import Config2

        class Config(Config, Config2):
            pass

        return Config


config = inherit_configs(some_condition)()
  • Related