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.setAttribute(Qt.WA_TransparentForMouseEvents, True)

can be translated in clojure code like:

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

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()
    .setAttribute(Qt.WA_TransparentForMouseEvents, True)\

comments powered by Disqus