Skip to content
Advertisement

How to avoid dummy clases during multiple inheritance with conditions

Is it possible to refactor multiinheritance without dummy classes? Maybe anybody have similar issue or have experienxe to tackle it, or at least tell me which way to look??

Code from __init__.py

from configuration.global_vars import IS_JENKINS_JOB, IS_TEST, IS_DOCKER, IS_TLF
from .base_runner import BaseRunner
from .base_runner_DOCKER import BaseRunnerDOCKER
from .base_runner_JENKINS import BaseRunnerJENKINS
from .base_runner_PROD import BaseRunnerPROD
from .base_runner_TEST import BaseRunnerTEST
from .base_runner_TLF import BaseRunnerTLF


class Dummy1:
    pass


class Dummy2:
    pass


class Dummy3:
    pass


class CombinedBase(
        BaseRunnerJENKINS if IS_JENKINS_JOB else Dummy1,
        BaseRunnerDOCKER if IS_DOCKER else Dummy2,
        BaseRunnerTLF if IS_TLF else Dummy3,
        BaseRunnerTEST if IS_TEST else BaseRunnerPROD,
        BaseRunner):
    pass

Advertisement

Answer

It is relatively easy to create a type dynamically in python.

For example:

# you can use whatever logic to dynamically create the list of bases
base_classes = [
  BaseRunnerJENKINS, 
  BaseRunnerTLF, 
  BaseRunner
]

# if you need to add custom methods to your new class:
class MyCustomClass:
    def method(self, *args):
        pass

# Create CombinedBase, inheriting from the MyCustomClass and the dynamic list.
CombinedBase = type('CombinedBase', (MyCustomClass, *base_classes), {})

print(CombinedBase.__bases__)
# (__main__.MyCustomClass, __main__.BaseRunnerJENKINS, __main__.BaseRunnerTLF, __main__.BaseRunner)
Advertisement