Metaclass question

Jp Calderone exarkun at intarweb.us
Wed Mar 12 14:10:29 EST 2003


On Wed, Mar 12, 2003 at 06:43:23PM +0000, Bojiro Kafir Tsava wrote:
> I need to achieve transparent import/instantiation of classes and modules.
> 
> Here's a summary
> 
> When I do:
> 
> import me.my.module.MyClass
> 
> should result in creation of a new python class "me.my.module.MyClass" which
> has a constructor:
> 
> class MyClass:
>     def __init__(self, *args):
>         self.extObj = extensionmodule.new(xxArg1, "MyClass")
> 

  This is something you want to use an import hook for, not a metaclass.

  Here is a very poor example:

    old_import = __import__
    def __import__(name, b, c, d):
        if name.startswith('foo.bar.baz'):
            return 'LA LA LA!'
        return old_import(name, b, c, d)
    __builtins__.__import__ = __import__

    import foo.bar.baz.bunk # Local name "foo" is now bound to "LA LA LA!"

  There is a more powerful and flexible mechanism in 2.3, but replacing
__import__ is probably all you need.

  Hope this helps,

  Jp

-- 
 up 9 days, 11:59, 6 users, load average: 0.23, 0.25, 0.20





More information about the Python-list mailing list