dynamic loading of modules in plugins?
John Arbash Meinel
john at arbash-meinel.com
Fri May 11 19:28:17 BST 2007
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
Ian Clatworthy wrote:
> I'm had a bit more trouble than I hoped for getting dynamic loading of
> modules working inside a bzr plugin. This worked fine:
>
> import scripts.script_common
> return scripts.script_common.script_suite()
>
> But this didn't:
>
> module_name = 'scripts.script_common'
> try:
> module = __import__(module_name, globals(), locals())
> except:
> # TODO: log exception properly
> info("failed to find module %s" % module_name)
> return None
> try:
> print "%r" % (module)
> fn = module.__dict__['script_suite']
> except:
> # TODO: log exception properly
> info("failed to find script_suite() in %s" % module)
> return None
> return fn.__call__()
>
> If I change the '.' in module_name to a '/', it works but the module
> str() is ...
>
> <module 'bzrlib.plugins.usertest.scripts/script_common' from
> '/home/ian/...'>
>
> Is this behaviour expected or a side effect of how we implement lazy
> importing of modules?
>
> Ian C.
>
>
Well, if you want 'script_suite' then you probabl ywant:
module = __import__(module_name, globals(), locals(), ['script_suite'])
fn = getattr(module, 'script_suite')
The specific tricks are:
__import__('foo.bar') will return 'foo' not 'bar'. Because when you do:
import bzrlib.foo
you get 'bzrlib' in your namespace.
However if you are doing "from bzrlib.foo import bar" you want 'foo' so
you can get the 'bar' attribute.
The other way to do it is:
def import_exactly(path):
"""path should be foo.bar.baz, this function will return 'baz'"""
parts = path.split('.')
mod = __import__(path)
for part in parts[:1]:
mod = getattr(mod, part)
return mod
(I don't know if we have a helper function to do this, I know Twisted does).
John
=:->
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.7 (Darwin)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org
iD8DBQFGRLXBJdeBCYSNAAMRAiJWAKCXt7/s25sQBvd8BiOxgGw+1G+EngCgmcKT
9XFVCcpDbTBfLXl36JT3ymQ=
=Q2Fa
-----END PGP SIGNATURE-----
More information about the bazaar
mailing list