Simplifying imports?

George Sakkis gsakkis at rutgers.edu
Tue Sep 13 13:46:31 EDT 2005


"Terry Hancock" <hancock at anansispaceworks.com> wrote:

> On Monday 12 September 2005 10:09 pm, chapolim-colorado at bol.com.br wrote:
> > I like to keep my classes each in a separate file with the same name of
> > the class. The problem with that is that I end up with multiple imports
> > in the beginning of each file, like this:
> >
> > from foo.Bar import Bar
> > from foo.Blah import Blah
> > from foo.Zzz import Zzz
> >
> > What I'd like to do would be to replace it all by a single line:
> >
> > from foo.* import *
> >
> > Of course, that doesn't work, but is there a way to do something like
> > that?
>
> Apparently "foo" is already a package defined using __init__.py,
> so you know about that part already.
>
> Just change its contents to read:
>
> from Bar import Bar
> from Blah import Blah
> from Zzz import Zzz

If you do this often or have lots of classes you want to import this
way, you could automate it:

#======== Foo.py ====================================
class Foo(object):
    pass

#======== Bar.py ====================================
class Bar(object):
    pass

#======== test.py ====================================
from autoimport import autoimport
autoimport("Foo","Bar")

if __name__ == '__main__':
    print Foo
    print Bar

# output:
# <class 'Foo.Foo'>
# <class 'Bar.Bar>

#======== autoimport.py ====================================
import sys

def autoimport(*modulenames):
    '''
    Perform the equivalent of "from XXX import XXX" for every
    module XXX in modulenames. In case of packaged modules, it is
    equivalent to "from XXX.YYY.ZZZ import ZZZ"
    '''
    caller_frame = sys._getframe(1)
    caller_locals = caller_frame.f_locals
    # import every module XXX and add the XXX.XXX object
    # to the caller's locals
    for name in modulenames:
        # in case of packaged modules A.B.C, make sure to import C
        module = __import__(name, caller_frame.f_globals,
                            caller_locals, [name])
        # extract 'C' from 'A.B.C'
        attribute = name[name.rfind('.')+1:]
        if hasattr(module,attribute):
            caller_locals[attribute] = getattr(module,attribute)

#==================================================

Or even better, forget about the braindead java restriction of one
class per file and organize your code as it makes more sense to you.

HTH,
George




More information about the Python-list mailing list