[C++-sig] Idea: Injecting methods using Python 2.4 decorator syntax

Ralf W. Grosse-Kunstleve rwgk at yahoo.com
Sun Feb 20 14:47:48 CET 2005

With reference to my previous posting


and this section in the Boost.Pyton documentation


Here is a neat alternative based on Python 2.4 decorators:

    # general purpose helper for injecting attributes
    class injector:

      def __init__(self, obj, attr):
        self.obj = obj
        self.attr = attr

      def __call__(self, attr_obj):
        setattr(self.obj, self.attr, attr_obj)

    class point:
      def __init__(self, (x,y)):
        self.xy = (x,y)

    @injector(point, "__str__")
    def attr_obj(self):
      return str(self.xy)

    p = point((1,2))
    print p

I am not sure about all the pros and cons compared to the
BoostPythonMetaclass approach shown in the Boost.Python documentation,
but at least I find it easier to understand and the injector is
completely independent of Boost.Python.


Do you Yahoo!? 
The all-new My Yahoo! - What will yours do?

More information about the Cplusplus-sig mailing list