[Baypiggies] Trivial OOP pattern problem

Ian Zimmerman itz at buug.org
Fri Jun 15 06:53:20 CEST 2012


I am writing some code using the cairo drawing library, or rather the
pycairo binding to it.  Unfortunately I sense a bit of API misdesign
with the binding.  To draw into a context ctx which I obtained somewhat
like this:

import cairo as C

ctx = C.Context(surface)

I am supposed to write a series of calls like this:

ctx.set_source_rgb(1.0, 1.0, 1.0)
ctx.rectangle(0.0, 0.0, float(rw), float(rh))
ctx.fill()
ctx.scale(sx, sy)

... and it piles up.  Each of these methods returns None, whilst it
should conceivably return self, adding a lot of convenience:

ctx.set_source_rgb(1.0, 1.0, 1.0).rectangle(0.0, 0.0, float(rw), float(rh)).fill()

I would like to write a wrapper class around Context to enable this
usage, but I don't know how to do that sanely.  Sure, I could do this:

class ContextWrapper(object):

      def __init__(self, surface):
          self.ctx = C.Context(surface)

      def fill(self):
          self.ctx.fill()
          return self

      def scale(self, sx, sy):
          self.ctx.scale(sx, sy)
          return self

          ...

but then I have to wrap each method explicitly, or at least each method
I use.  I don't consider that sane.

Is there a trick I am missing, perhaps using __dict__ or __getattr__ by
which I could wrap all the methods wholesale?

-- 
Ian Zimmerman
gpg public key: 1024D/C6FF61AD
fingerprint: 66DC D68F 5C1B 4D71 2EE5  BD03 8A00 786C C6FF 61AD
http://www.gravatar.com/avatar/c66875cda51109f76c6312f4d4743d1e.png
Rule 420: All persons more than eight miles high to leave the court.


More information about the Baypiggies mailing list