delegate functions to member

Chris Rebert clp2 at rebertia.com
Tue Aug 10 05:19:10 EDT 2010


On Tue, Aug 10, 2010 at 2:01 AM, Ulrich Eckhardt
<eckhardt at satorlaser.com> wrote:
> Hi!
>
> I have an extension module (a plugin written with Boost.Python) and around
> that a wrapper class that adapts a few things. Since the module is a
> plugin, there are multiple implementations of this. What I'm currently
> doing is this:
>
>  plugin = __import__(plugin_name)
>
>  class PluginWrapper(plugin.PluginClass):
>     ...
>
> This means that the definition of class PluginWrapper actually depends on
> the previously loaded module. What I would like to do is to define the
> wrapper just once and instead pass the plugin module to the constructor:
>
>  class PluginWrapper(object):
>    ...
>  plugin = __import__(plugin_name)
>  instance = PluginWrapper(plugin)
>
>
> Now, I use the wrapper to make some function more friendly (e.g. default
> parameters, keyword-parameters, wrapping raw handles) but I want other
> functions from the baseclass to remain untouched. If I use a baseclass,
> this lookup is automatic. However, when I pass the instance to the
> constructor, I have to store it in a member, and then I have to add code
> for every function only to delegate it to that member.
>
> Is there an easy and generic way out of this?

Create the subclass(es) dynamically:

def wrap(plug_in):
    class PluginWrapper(plug_in.PluginClass):
        ...
    return PluginWrapper

plugin = __import__(plugin_name)
WrappedPlugin = wrap(plugin)

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list