Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit d4f1d20

Browse files
author
Greg Stein
committed
shift demo importers to importers.py (destined for Demo/ ?)
switch to isinstance() rather than direct type comparisons removing chaining concept update ImportManager.install() to take an optional namespace to install itself in. this will be useful for setting up rexec environments. minor comment nits
1 parent 18c05f2 commit d4f1d20

1 file changed

Lines changed: 16 additions & 227 deletions

File tree

Lib/imputil.py

Lines changed: 16 additions & 227 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
# Gordon McMillan.
1111
#
1212
# This module is maintained by Greg and is available at:
13-
# http://www.lyra.org/greg/python/imputil.py
13+
# http://www.lyra.org/greg/python/
1414
#
1515
# Since this isn't in the Python distribution yet, we'll use the CVS ID
1616
# for tracking:
@@ -28,20 +28,21 @@
2828
import marshal
2929

3030
_StringType = type('')
31-
_ModuleType = type(sys)
31+
_ModuleType = type(sys) ### doesn't work in JPython...
3232

3333
class ImportManager:
3434
"Manage the import process."
3535

36-
def install(self):
37-
### warning: Python 1.6 will have a different hook mechanism; this
38-
### code will need to change.
39-
self.__chain_import = __builtin__.__import__
40-
self.__chain_reload = __builtin__.reload
41-
__builtin__.__import__ = self._import_hook
36+
def install(self, namespace=vars(__builtin__)):
37+
"Install this ImportManager into the specified namespace."
38+
39+
if isinstance(namespace, _ModuleType):
40+
namespace = vars(namespace)
41+
42+
### Note that we have no notion of "uninstall" or "chaining"
43+
namespace['__import__'] = self._import_hook
4244
### fix this
43-
#__builtin__.reload = None
44-
#__builtin__.reload = self._reload_hook
45+
#namespace['reload'] = self._reload_hook
4546

4647
def add_suffix(self, suffix, importer):
4748
assert isinstance(importer, SuffixImporter)
@@ -94,7 +95,6 @@ def _import_hook(self, fqname, globals=None, locals=None, fromlist=None):
9495
if not top_module:
9596
# the topmost module wasn't found at all.
9697
raise ImportError, 'No module named ' + fqname
97-
return self.__chain_import(name, globals, locals, fromlist)
9898

9999
# fast-path simple imports
100100
if len(parts) == 1:
@@ -125,7 +125,6 @@ def _import_hook(self, fqname, globals=None, locals=None, fromlist=None):
125125
# means that something else imported the module, and we have no knowledge
126126
# of how to get sub-modules out of the thing.
127127
raise ImportError, 'No module named ' + fqname
128-
return self.__chain_import(name, globals, locals, fromlist)
129128

130129
def _determine_import_context(self, globals):
131130
"""Returns the context in which a module should be imported.
@@ -170,7 +169,7 @@ def _import_top_module(self, name):
170169
# scan sys.path looking for a location in the filesystem that contains
171170
# the module, or an Importer object that can import the module.
172171
for item in sys.path:
173-
if type(item) == _StringType:
172+
if isinstance(item, _StringType):
174173
module = self.fs_imp.import_from_dir(item, name)
175174
else:
176175
module = item.import_top(name)
@@ -185,7 +184,8 @@ def _reload_hook(self, module):
185184
# importer), but at least we can validate that it's ours to reload
186185
importer = module.__dict__.get('__importer__')
187186
if not importer:
188-
return self.__chain_reload(module)
187+
### oops. now what...
188+
pass
189189

190190
# okay. it is using the imputil system, and we must delegate it, but
191191
# we don't know what to do (yet)
@@ -269,7 +269,7 @@ def _import_one(self, parent, modname, fqname):
269269

270270
def _process_result(self, (ispkg, code, values), fqname):
271271
# did get_code() return an actual module? (rather than a code object)
272-
is_module = type(code) is _ModuleType
272+
is_module = isinstance(code, _ModuleType)
273273

274274
# use the returned module, or create a new one to exec code into
275275
if is_module:
@@ -379,15 +379,12 @@ def get_code(self, parent, modname, fqname):
379379
# Some handy stuff for the Importers
380380
#
381381

382-
# byte-compiled file suffic character
382+
# byte-compiled file suffix character
383383
_suffix_char = __debug__ and 'c' or 'o'
384384

385385
# byte-compiled file suffix
386386
_suffix = '.py' + _suffix_char
387387

388-
# the C_EXTENSION suffixes
389-
_c_suffixes = filter(lambda x: x[2] == imp.C_EXTENSION, imp.get_suffixes())
390-
391388
def _compile(pathname, timestamp):
392389
"""Compile (and cache) a Python source file.
393390
@@ -483,202 +480,6 @@ def _timestamp(pathname):
483480
return None
484481
return long(s[8])
485482

486-
def _fs_import(dir, modname, fqname):
487-
"Fetch a module from the filesystem."
488-
489-
pathname = _os_path_join(dir, modname)
490-
if _os_path_isdir(pathname):
491-
values = { '__pkgdir__' : pathname, '__path__' : [ pathname ] }
492-
ispkg = 1
493-
pathname = _os_path_join(pathname, '__init__')
494-
else:
495-
values = { }
496-
ispkg = 0
497-
498-
# look for dynload modules
499-
for desc in _c_suffixes:
500-
file = pathname + desc[0]
501-
try:
502-
fp = open(file, desc[1])
503-
except IOError:
504-
pass
505-
else:
506-
module = imp.load_module(fqname, fp, file, desc)
507-
values['__file__'] = file
508-
return 0, module, values
509-
510-
t_py = _timestamp(pathname + '.py')
511-
t_pyc = _timestamp(pathname + _suffix)
512-
if t_py is None and t_pyc is None:
513-
return None
514-
code = None
515-
if t_py is None or (t_pyc is not None and t_pyc >= t_py):
516-
file = pathname + _suffix
517-
f = open(file, 'rb')
518-
if f.read(4) == imp.get_magic():
519-
t = struct.unpack('<I', f.read(4))[0]
520-
if t == t_py:
521-
code = marshal.load(f)
522-
f.close()
523-
if code is None:
524-
file = pathname + '.py'
525-
code = _compile(file, t_py)
526-
527-
values['__file__'] = file
528-
return ispkg, code, values
529-
530-
531-
######################################################################
532-
#
533-
# Simple function-based importer
534-
#
535-
class FuncImporter(Importer):
536-
"Importer subclass to use a supplied function rather than method overrides."
537-
def __init__(self, func):
538-
self.func = func
539-
def get_code(self, parent, modname, fqname):
540-
return self.func(parent, modname, fqname)
541-
542-
def install_with(func):
543-
FuncImporter(func).install()
544-
545-
546-
######################################################################
547-
#
548-
# Base class for archive-based importing
549-
#
550-
class PackageArchiveImporter(Importer):
551-
"""Importer subclass to import from (file) archives.
552-
553-
This Importer handles imports of the style <archive>.<subfile>, where
554-
<archive> can be located using a subclass-specific mechanism and the
555-
<subfile> is found in the archive using a subclass-specific mechanism.
556-
557-
This class defines two hooks for subclasses: one to locate an archive
558-
(and possibly return some context for future subfile lookups), and one
559-
to locate subfiles.
560-
"""
561-
562-
def get_code(self, parent, modname, fqname):
563-
if parent:
564-
# the Importer._finish_import logic ensures that we handle imports
565-
# under the top level module (package / archive).
566-
assert parent.__importer__ == self
567-
568-
# if a parent "package" is provided, then we are importing a sub-file
569-
# from the archive.
570-
result = self.get_subfile(parent.__archive__, modname)
571-
if result is None:
572-
return None
573-
if type(result) == type(()):
574-
return (0,) + result
575-
return 0, result
576-
577-
# no parent was provided, so the archive should exist somewhere on the
578-
# default "path".
579-
archive = self.get_archive(modname)
580-
if archive is None:
581-
return None
582-
return 1, "", {'__archive__':archive}
583-
584-
def get_archive(self, modname):
585-
"""Get an archive of modules.
586-
587-
This method should locate an archive and return a value which can be
588-
used by get_subfile to load modules from it. The value may be a simple
589-
pathname, an open file, or a complex object that caches information
590-
for future imports.
591-
592-
Return None if the archive was not found.
593-
"""
594-
raise RuntimeError, "get_archive not implemented"
595-
596-
def get_subfile(self, archive, modname):
597-
"""Get code from a subfile in the specified archive.
598-
599-
Given the specified archive (as returned by get_archive()), locate
600-
and return a code object for the specified module name.
601-
602-
A 2-tuple may be returned, consisting of a code object and a dict
603-
of name/values to place into the target module.
604-
605-
Return None if the subfile was not found.
606-
"""
607-
raise RuntimeError, "get_subfile not implemented"
608-
609-
610-
class PackageArchive(PackageArchiveImporter):
611-
"PackageArchiveImporter subclass that refers to a specific archive."
612-
613-
def __init__(self, modname, archive_pathname):
614-
self.__modname = modname
615-
self.__path = archive_pathname
616-
617-
def get_archive(self, modname):
618-
if modname == self.__modname:
619-
return self.__path
620-
return None
621-
622-
# get_subfile is passed the full pathname of the archive
623-
624-
625-
######################################################################
626-
#
627-
# Emulate the standard directory-based import mechanism
628-
#
629-
class DirectoryImporter(Importer):
630-
"Importer subclass to emulate the standard importer."
631-
632-
def __init__(self, dir):
633-
self.dir = dir
634-
635-
def get_code(self, parent, modname, fqname):
636-
if parent:
637-
dir = parent.__pkgdir__
638-
else:
639-
dir = self.dir
640-
641-
# defer the loading of OS-related facilities
642-
if not _os_stat:
643-
_os_bootstrap()
644-
645-
# Return the module (and other info) if found in the specified
646-
# directory. Otherwise, return None.
647-
return _fs_import(dir, modname, fqname)
648-
649-
def __repr__(self):
650-
return '<%s.%s for "%s" at 0x%x>' % (self.__class__.__module__,
651-
self.__class__.__name__,
652-
self.dir,
653-
id(self))
654-
655-
######################################################################
656-
#
657-
# Emulate the standard path-style import mechanism
658-
#
659-
class PathImporter(Importer):
660-
def __init__(self, path=sys.path):
661-
self.path = path
662-
663-
# we're definitely going to be importing something in the future,
664-
# so let's just load the OS-related facilities.
665-
if not _os_stat:
666-
_os_bootstrap()
667-
668-
def get_code(self, parent, modname, fqname):
669-
if parent:
670-
# we are looking for a module inside of a specific package
671-
return _fs_import(parent.__pkgdir__, modname, fqname)
672-
673-
# scan sys.path, looking for the requested module
674-
for dir in self.path:
675-
result = _fs_import(dir, modname, fqname)
676-
if result:
677-
return result
678-
679-
# not found
680-
return None
681-
682483

683484
######################################################################
684485
#
@@ -792,18 +593,6 @@ def import_file(self, filename, finfo, fqname):
792593

793594
######################################################################
794595

795-
def _test_dir():
796-
"Debug/test function to create DirectoryImporters from sys.path."
797-
path = sys.path[:]
798-
path.reverse()
799-
for d in path:
800-
DirectoryImporter(d).install()
801-
802-
def _test_revamp():
803-
"Debug/test function for the revamped import system."
804-
PathImporter().install()
805-
BuiltinImporter().install()
806-
807596
def _print_importers():
808597
items = sys.modules.items()
809598
items.sort()

0 commit comments

Comments
 (0)