newbie question: getting a module in a package

Mike Fletcher mcfletch at vrtelecom.com
Thu Sep 23 01:02:30 EDT 1999


PythonWin 1.5.2 (#0, Apr 13 1999, 10:51:12) [MSC 32 bit (Intel)] on win32
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
Portions Copyright 1994-1999 Mark Hammond (MHammond at skippinet.com.au)
>>> __import__( 'mcf.pars.int', {},{},['mcf','pars','int'] )
<module 'mcf.pars.int' from 'mcf\pars\int\__init__.pyc'>
>>> __import__( 'mcf.pars.int', {},{},['mcf'] )
<module 'mcf.pars.int' from 'mcf\pars\int\__init__.pyc'>
>>> __import__( 'mcf.pars.int', {},{},['blah'] )
<module 'mcf.pars.int' from 'mcf\pars\int\__init__.pyc'>
>>>

It's rather awkward looking, but it seems to work here... the operation
seems a little arbitrary to me (why bother to check for non-empty list if
you're not using the values for anything?)  It's documented, I just think
it's weird :) .

Would agree that a FAQ update would seem in order though.  The loop is even
weirder ;) .

Cheers,
Mike

-----Original Message-----
From: python-list-request at cwi.nl [mailto:python-list-request at cwi.nl]On
Behalf Of Jim Althoff
Sent: September 22, 1999 7:57 PM
To: python-list at cwi.nl
Subject: newbie question: getting a module in a package


FAQ 4.85 suggests the following for
importing a module in a package
(s = "x.y.z"):

m = __import__(s)

for i in string.split(s, ".")[1:]:
    m = getattr(m, i)


Doesn't the following work equally well?
(And is more obvious and faster?)

__import__(s)
m = sys.modules[s]

Perhaps I'm missing something?

Jim








More information about the Python-list mailing list