On Tue, 11 Dec 2007 08:57:16 -0800, George Sakkis wrote: > On Dec 10, 11:07 pm, Stargaming <[EMAIL PROTECTED]> wrote: >> On Mon, 10 Dec 2007 19:27:43 -0800, George Sakkis wrote: >> > On Dec 10, 2:11 pm, Stargaming <[EMAIL PROTECTED]> wrote: [snip] >> >> Even though I do not qualify for the job, I came up with this >> >> (<wink>) code (modified list values for demonstration, mixed >> >> together from previous post and original task): >> >> >> print '\n'.join('%s: %d'%(x,len(list(y))) for x,y in __import__ >> >> ('itertools').groupby(sorted(__import__('xml').dom.minidom.parse >> >> (__import__('urllib').urlopen('http://api.etsy.com/feeds/ >> >> xml_user_details.php?id=%d'%i)).getElementsByTagName('city') >> >> [0].lastChild.data.title() for i in (71234, 729, 42346, 77290, 729, >> >> 729)))) >> [snip] >> >> > Alas, it's not: >> >> > AttributeError: 'module' object has no attribute 'dom' [snip] >> Heh, yes. I did the same error as the participant before me -- test it >> in a premodified environment. A fix is easy, __import__ >> 'xml.dom.minidom' instead of 'xml'. :-) > > 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'> You can observe the change pretty well in `sys.modules`:: >>> __import__('xml') <module 'xml' from '/usr/lib/python2.5/xml/__init__.pyc'> >>> import sys >>> sys.modules.keys() The result will be a few core modules and the module `xml`. When importing `xml.dom.minidom`, though, this imports a lot more files:: >>> __import__('xml.dom.minidom') <module 'xml' from '/usr/lib/python2.5/xml/__init__.pyc'> >>> import sys >>> sys.modules.keys() Among them, there are `xml`, `xml.dom` and `xml.dom.minidom`. Having these modules imported, `__import__('xml.dom.minidom').dom.minidom` becomes a perfectly valid access to the xml/xml.dom packages. So, your check is correct, importing xml.dom.minidom and xml both give a reference to `xml` but the import machinery is invoked to import its contents, as well, when explicitly told to. -- http://mail.python.org/mailman/listinfo/python-list