PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, November 22, 2022

[FIXED] How to avoid dummy clases during multiple inheritance with conditions

 November 22, 2022     dynamic-typing, multiple-conditions, multiple-inheritance, python     No comments   

Issue

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

Solution

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)


Answered By - Rodrigo Rodrigues
Answer Checked By - Willingham (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing