In Python, how can I add another module to an already existing variable that contains one?

Question:

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.

Asked By: Immortal

||

Answers:

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 BaseConfig:
    att = "hello world"


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

        class Config(BaseConfig, Config1):
            pass

        return Config
    else:
        from config2 import Config2

        class Config(BaseConfig, Config2):
            pass

        return Config


config = inherit_configs(some_condition)()
Answered By: iced
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.