Source

pysnmp-patches / zipmibsource_import

Full commit
# HG changeset patch
# Parent d34d41dbc5f6f37ea51637f8b7a34e73b74987ea
# User Floris Bruynooghe <flub@devork.be>
# Date 1324243064 -3600

Use a slightly better library call to perform the import

The problem with using the bare __import__ is that the way it was used
it would attempt relative imports first.  This means any modules or
packages in the pysnmp.smi package would shadow those names on the
toplevel, which can be surprising.

diff --git a/pysnmp/smi/builder.py b/pysnmp/smi/builder.py
--- a/pysnmp/smi/builder.py
+++ b/pysnmp/smi/builder.py
@@ -9,6 +9,39 @@ if sys.version_info[0] <= 2:
 else:
     classTypes = (type,)
 
+try:
+    from importlib import import_module
+except ImportError:
+    # These two functions are copied from importlib.__init__ in Python 2.7
+
+    def _resolve_name(name, package, level):
+        if not hasattr(package, 'rindex'):
+            raise ValueError("'package' not set to a string")
+        dot = len(package)
+        for x in xrange(level, 1, -1):
+            try:
+                dot = package.rindex('.', 0, dot)
+            except ValueError:
+                raise ValueError("attempted relative import beyond top-level "
+                                  "package")
+        return "%s.%s" % (package[:dot], name)
+
+
+    def import_module(name, package=None):
+        if name.startswith('.'):
+            if not package:
+                raise TypeError(
+                    "relative imports require the 'package' argument")
+            level = 0
+            for character in name:
+                if character != '.':
+                    break
+                level += 1
+            name = _resolve_name(name[level:], package, level)
+        __import__(name)
+        return sys.modules[name]
+
+
 class __AbstractMibSource:
     def __init__(self, srcName):
         self._srcName = srcName
@@ -94,7 +127,7 @@ class __AbstractMibSource:
 class ZipMibSource(__AbstractMibSource):
     def _init(self):
         try:
-            p = __import__(self._srcName, globals(), locals(), ['__init__'])
+            p = import_module(self._srcName)
             if hasattr(p, '__loader__') and hasattr(p.__loader__, '_files'):
                 self.__loader = p.__loader__
                 self._srcName = self._srcName.replace('.', os.sep)