[Python-checkins] r52155 - sandbox/trunk/import_in_py/importer.py sandbox/trunk/import_in_py/test_importer.py

brett.cannon python-checkins at python.org
Thu Oct 5 00:55:02 CEST 2006


Author: brett.cannon
Date: Thu Oct  5 00:55:01 2006
New Revision: 52155

Added:
   sandbox/trunk/import_in_py/importer.py   (contents, props changed)
   sandbox/trunk/import_in_py/test_importer.py   (contents, props changed)
Log:
Add built-in importer with tests.


Added: sandbox/trunk/import_in_py/importer.py
==============================================================================
--- (empty file)
+++ sandbox/trunk/import_in_py/importer.py	Thu Oct  5 00:55:01 2006
@@ -0,0 +1,58 @@
+"""Re-implementation of import machinery in Python source code.
+
+When developing please keep imports down to a minimum.  There is a basic
+bootstrapping problem of importing in import!  It is best to keep imports to
+only built-in modules (see sys.builtin_module_names) as having the built-in
+importer written in C is fairly straight-forward.
+
+References on import:
+* Language reference
+    http://docs.python.org/ref/import.html
+* PEP 302: New Import Hooks
+    http://www.python.org/dev/peps/pep-0302/
+* __import__ function
+    http://docs.python.org/lib/built-in-funcs.html
+
+"""
+import imp
+import sys
+
+
+class BuiltinImporter(object):
+
+    """sys.meta_path class for importing built-in modules.
+    
+    Use static and classmethods as no purpose is served by having instances of
+    this class.
+    
+    """
+
+    @classmethod
+    def find_module(cls, fullname, path=None):
+        """See if import is for a built-in module.
+
+        Since built-in modules should never have a path, short-circuit if one
+        is specified.
+
+        """
+        if path is not None:
+            return None
+        # Could also check sys.builtin_module_names to see if the import is for
+        # a built-in module.
+        if imp.is_builtin(fullname):
+            return cls
+        else:
+            return None
+
+    @staticmethod
+    def load_module(fullname, path=None):
+        """Load a built-in module.
+
+        'imp' code for loading a built-in modules handles the setting of a
+        module in sys.modules before initializing the module.
+
+        """
+        try:
+            return sys.modules[fullname]
+        except KeyError:
+            return imp.init_builtin(fullname)

Added: sandbox/trunk/import_in_py/test_importer.py
==============================================================================
--- (empty file)
+++ sandbox/trunk/import_in_py/test_importer.py	Thu Oct  5 00:55:01 2006
@@ -0,0 +1,49 @@
+import unittest
+from test import test_support
+import importer
+import sys
+
+class BuiltinImporterTests(unittest.TestCase):
+
+    """Test the built-in module importer."""
+
+    def test_find_module_basic(self):
+        # Make sure only built-in modules are found.
+        for name in sys.builtin_module_names:
+            self.failUnless(importer.BuiltinImporter.find_module(name))
+        self.failUnless(not importer.BuiltinImporter.find_module('time'),
+                        'incorrectly found an extension module')
+        self.failUnless(not importer.BuiltinImporter.find_module('token'),
+                        'incorrectly found a Python module')
+
+    def test_find_module_path_shortcut(self):
+        # Test short-circuiting of finding a module if 'path' argument is given
+        # a value.
+        self.failUnless(not importer.BuiltinImporter.find_module('sys', ''))
+
+    def test_load_module_prev_import_check(self):
+        # If a module is already in 'sys' it should be returned without being
+        # re-initialized.
+        self.failUnlessEqual(importer.BuiltinImporter.load_module('sys'),
+                             sys.modules['sys'])
+
+    def test_load_module_new_import(self):
+        # Make sure importing of a built-in that was not done before works
+        # properly.
+        try:
+            del sys.modules['sys']
+        except KeyError:
+            pass
+        sys_module = importer.BuiltinImporter.load_module('sys')
+        self.failUnless(sys_module)
+        self.failUnless(hasattr(sys_module, 'version'))
+
+
+def test_main():
+    test_support.run_unittest(
+                BuiltinImporterTests,
+            )
+
+
+if __name__ == '__main__':
+    test_main()


More information about the Python-checkins mailing list