Add support for dotted module names to readmodule().

This commit is contained in:
Guido van Rossum 1998-10-12 15:21:38 +00:00
parent 1c5fb1cd1b
commit 7a840e8d50
1 changed files with 26 additions and 18 deletions

View File

@ -65,13 +65,22 @@ class Class:
def _addmethod(self, name, lineno): def _addmethod(self, name, lineno):
self.methods[name] = lineno self.methods[name] = lineno
def readmodule(module, path = []): def readmodule(module, path=[], inpackage=0):
'''Read a module file and return a dictionary of classes. '''Read a module file and return a dictionary of classes.
Search for MODULE in PATH and sys.path, read and parse the Search for MODULE in PATH and sys.path, read and parse the
module and return a dictionary with one entry for each class module and return a dictionary with one entry for each class
found in the module.''' found in the module.'''
i = string.rfind(module, '.')
if i >= 0:
# Dotted module name
package = module[:i]
submodule = module[i+1:]
parent = readmodule(package, path, inpackage)
child = readmodule(submodule, parent['__path__'], 1)
return child
if _modules.has_key(module): if _modules.has_key(module):
# we've seen this module before... # we've seen this module before...
return _modules[module] return _modules[module]
@ -83,21 +92,20 @@ def readmodule(module, path = []):
# search the path for the module # search the path for the module
f = None f = None
suffixes = imp.get_suffixes() if inpackage:
for dir in path + sys.path:
for suff, mode, type in suffixes:
file = os.path.join(dir, module + suff)
try: try:
f = open(file, mode) f, file, (suff, mode, type) = \
except IOError: imp.find_module(module, path)
pass except ImportError:
else: f = None
# found the module if f is None:
break fullpath = path + sys.path
if f: f, file, (suff, mode, type) = imp.find_module(module, fullpath)
break if type == imp.PKG_DIRECTORY:
if not f: dict = {'__path__': [file]}
raise IOError, 'module ' + module + ' not found' _modules[module] = dict
# XXX Should we recursively look for submodules?
return dict
if type != imp.PY_SOURCE: if type != imp.PY_SOURCE:
# not Python source, can't do anything with this module # not Python source, can't do anything with this module
f.close() f.close()
@ -130,7 +138,7 @@ def readmodule(module, path = []):
try: try:
# recursively read the # recursively read the
# imported module # imported module
d = readmodule(n, path) d = readmodule(n, path, inpackage)
except: except:
print 'module',n,'not found' print 'module',n,'not found'
pass pass
@ -142,7 +150,7 @@ def readmodule(module, path = []):
names = string.splitfields(res.group('imp'), ',') names = string.splitfields(res.group('imp'), ',')
try: try:
# recursively read the imported module # recursively read the imported module
d = readmodule(mod, path) d = readmodule(mod, path, inpackage)
except: except:
print 'module',mod,'not found' print 'module',mod,'not found'
continue continue