Job Offer: Python Ninja or Pirate!

George Sakkis george.sakkis at gmail.com
Fri Dec 14 11:55:55 EST 2007


On Dec 14, 9:57 am, Stargaming <stargam... at gmail.com> wrote:
> On Tue, 11 Dec 2007 08:57:16 -0800, George Sakkis wrote:

> > Closer, but still wrong; for some weird reason, __import__ for modules
> > in packages returns the top level package by default; you have to use
> > the 'fromlist' argument:
>
> >>>> __import__('xml.dom.minidom') is __import__('xml')
> > True
>
> >>>> __import__('xml.dom.minidom', fromlist=True)
> > <module 'xml.dom.minidom' from '/usr/local/lib/python2.5/xml/dom/
> > minidom.pyc'>
>
> > George
>
> No, it's perfectly right::
>
>     >>> __import__('xml.dom.minidom').dom.minidom
>     <module 'xml.dom.minidom' from
>     '/usr/lib/python2.5/xml/dom/minidom.pyc'>

Sure, if you remember to repeat all.the.subpackages.after.the.top.
Instead of __import__ I use a more intuitive and general version that
doesn't stop at module boundaries but acts as getattr() within a
module:

for name in ['xml',
             'xml.dom',
             'xml.dom.minidom',
             'xml.dom.minidom.parse',
             'xml.dom.minidom.parse.__name__']:
    print '%s: %r\n' % (name, import_name(name))


#### output

xml: <module 'xml' from '/usr/local/lib/python2.5/xml/__init__.pyc'>

xml.dom: <module 'xml.dom' from '/usr/local/lib/python2.5/xml/dom/
__init__.pyc'>

xml.dom.minidom: <module 'xml.dom.minidom' from '/usr/local/lib/
python2.5/xml/dom/minidom.pyc'>

xml.dom.minidom.parse: <function parse at 0xb7d40614>

xml.dom.minidom.parse.__name__: 'parse'


#=== import_name =============================

def import_name(name, globals={}, locals={}):
    prefix,sep,tail = name.partition('.')
    obj = __import__(prefix, globals, locals)
    is_module = True
    while sep:
        head,sep,tail = tail.partition('.')
        if is_module:
            prefix += '.' + head
            try: __import__(prefix, globals, locals)
            except ImportError: is_module = False
        try: obj = getattr(obj,head)
        except AttributeError:
            raise ImportError('No name %s' % name)
    return obj


George



More information about the Python-list mailing list