Unsolved Decamelizing method names
-
I wrote a small function that I use when instantiating a widget to make it possible to invoke methods using PEP8 method names equivalent to the standard camelcase ones. It works in every situation I have used it, but I am wondering whether anyone who is more familiar with the internal workings of Qt for Python can see where this technique will cause trouble. It does not decamelize instances of classes delivered by other classes (e.g., the QStyle instance returned by QWidget.style), although it might work in that case to monkey patch the instance with the same
__getattr__
provided by the DeCamel class below. But even if this technique is not a complete solution to the camelcase issue, it does go a long way to improving the appearance of the code.import types from PySide2.QtWidgets import QApplication, QLineEdit def Q(qclass): class DeCamel(qclass): def __getattr__(self, attr): attr_nocap, *attr_caps = attr.split('_') attr_camel = [attr_nocap] + [a.capitalize() for a in attr_caps] method = getattr(qclass, ''.join(attr_camel)) return types.MethodType(method, self) DeCamel.__name__ = qclass.__name__ DeCamel.__qualname__ = qclass.__qualname__ return DeCamel def test(): lineedit = Q(QLineEdit)() lineedit.setText("test") lineedit.set_text("test") if __name__ == '__main__': app = QApplication(sys.argv) test() ``