unifying many packages under one name

E

Eric S. Johansson

I have a collection of packages and I want to put them under single unifying
name. my goal is to reduce namespace pollution and make all these packages
accessible as 'import vvv.aaa'. In more detail, if I have packages 'aaa' and
'bbb', what do I do to put those packages under unifying name such as 'vvv'?
the only way I can see to do it is to create 'vvv' as a directory with its own
__init__.py but I'm not sure that were work right either.


thanks.
 
P

Peter Otten

Eric said:
I have a collection of packages and I want to put them under single
unifying
name. my goal is to reduce namespace pollution and make all these
packages accessible as 'import vvv.aaa'. In more detail, if I have
packages 'aaa' and 'bbb', what do I do to put those packages under
unifying name such as 'vvv'? the only way I can see to do it is to create
'vvv' as a directory with its own __init__.py but I'm not sure that were
work right either.

Of course you could make a module vvv.py with lots of import statements

import aaa
import bbb
....
import zzz

but then all submodules are imported eagerly with

import vvv

And then there's the hack

import sys

class Importer(object):
def __getattr__(self, name):
module = __import__(name) # you can do anything here
setattr(self, name, module)
return module

sys.modules["vvv"] = Importer()

Peter
 
J

James Stroud

Eric said:
I have a collection of packages and I want to put them under single
unifying name. my goal is to reduce namespace pollution and make all
these packages accessible as 'import vvv.aaa'. In more detail, if I have
packages 'aaa' and 'bbb', what do I do to put those packages under
unifying name such as 'vvv'? the only way I can see to do it is to
create 'vvv' as a directory with its own __init__.py but I'm not sure
that were work right either.


thanks.

I don't see why it would be a problem:


py> import os
py> for afile in os.listdir('pypack'):
.... if not afile.endswith('pyc'):
.... print '# %s' % afile
.... print open(os.path.join('pypack', afile)).read().strip()
.... print '# end of file\n\n'
....
# __init__.py
from mod1 import x
from mod2 import y
# end of file


# mod1.py
x = 14
# end of file


# mod2.py
y = 42
# end of file


py> import pypack
py> dir(pypack)

['__builtins__',
'__doc__',
'__file__',
'__name__',
'__path__',
'mod1',
'mod2',
'x',
'y']
py> pypack.mod1
<module 'pypack.mod1' from 'pypack/mod1.py'>


James
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,967
Messages
2,570,148
Members
46,694
Latest member
LetaCadwal

Latest Threads

Top