Commits

Floris Bruynooghe committed 1992863

Add patch for relative import

  • Participants
  • Parent commits 9d3786f

Comments (0)

Files changed (2)

+zipmibsource_import
 # Placed by Bitbucket

File zipmibsource_import

+# HG changeset patch
+# Parent 221e24b5b1e699a10a4b08bfd84c68524ccf0b56
+# 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
+@@ -86,9 +119,7 @@ class __AbstractMibSource:
+             
+ class ZipMibSource(__AbstractMibSource):
+     def _init(self):
+-        p = __import__(
+-            self._srcName, globals(),locals(), self._srcName.split('.')
+-            )
++        p = import_module(self._srcName)
+         if hasattr(p, '__loader__'):
+             self.__loader = p.__loader__
+             self._srcName = self._srcName.replace('.', os.sep)