Python Forum

Full Version: Design question will __call__
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,
I am currently refactoring my API. I have been reading some because like Robert C. Martin clean code, and I am trying to right a cleaner code. So I came up with this:

from PySide2 import QtWidgets, QtCore

class Widget(QtWidgets.QWidget):

    def __call__(self, **kwargs):
        for key in kwargs:
            if key == "t":
                self.title()
            if key == "n":
                self.widgetName()
            if key == "c":
                self.color()
            if key == "tt":
                self.toolTip()
            if key == "p":
                self.parent()

    def title(self):
        print "this will give the widget a title"

    def widgetName(self):
        print "this will give the widget a name"
        
    def color(self):
        print "this will give the widget color"

    def toolTip(self):
        print "this will pop up a tooltip"
        
    def parent(self):
        print "this will give a parent to the widget"
        


class PushButton(Widget):

    def __call__(self, **kwargs):
        print "this creates a button"
        super(PushButton, self).__call__(**kwargs)


class ComboBox(Widget):

    def __call__(self, **kwargs):
        print "this creates a comboBox"
        super(ComboBox, self).__call__(**kwargs)


# Run
pushBtn = PushButton()
pushBtn(t="push me", n="pushBtnA")
pushBtn(t="push me too", n="pushBtB", c=("rgb(100, 25, 75)"), p=None, tt="I am here to help")


cmbBox = ComboBox()
cmbBox(n="comboBoxA")
So as you can see I have created an abstract class thas is inherited by diferent type of widgets. I would like to know what do you think about that design. What I like about is that in one line I can set an entire widget, and that it works with multiple types of widgets. But According to clean code I might be breaking 2 rules here:
. the __call__ in the base class is too long and have multiple if statements.
. methods should maximum 3 arguments, with that design I can add as many as I want.

what do you think?

Thanks
The complicated if structures can be replaced by a dictionary:

    def __call__(self, **kwargs):
        methods = {'t': self.title, 'n': self.widgetName, 'c': self.color, 'p': self.parent}
        for key in kwargs:
            methods[key]()
or as a class attribute:

class Widget(QtWidgets.QWidget):

    methods = {'t': 'title', 'n': 'widgetName', 'c': 'color', 'p': 'parent'}

    def __call__(self, **kwargs):
        for key in kwargs:
            getattr(self, methods[key])()