doto from clojure in python


When i writing code in clojure i can use good macro – doto.

With whom python code like:

window = QMainWindow()
window.setTitle(TITLE)
window.setWindowFlags(Qt.FramelessWindowHint)
window.setAttribute(Qt.WA_TransparentForMouseEvents, True)
window.show()

can be translated in clojure code like:

(doto (QMainWindow.)
      (.setTitle title)
      (.setWindowFlags Qt/FramelessWindowHint)
      (.setAttribute Qt/WA_TransparentForMouseEvents True)
      (.show))

And i wrote hackish class for doing something similar in python.

from functools import partial


class DoTo(object):
    def __init__(self, obj):
        self._obj = obj

    def _do(self, name, *args, **kwargs):
        getattr(self._obj, name)(*args, **kwargs)
        return self

    def __getattr__(self, item):
        return partial(self._do, item)

With method chaining we can emulate behavior of clojure doto:

window = QMainWindow()
DoTo(window)\
    .setTitle(TITLE)\
    .setWindowFlags(Qt.FramelessWindowHint)\
    .setAttribute(Qt.WA_TransparentForMouseEvents, True)\
    .show()


comments powered by Disqus