Anonymous avatar Anonymous committed b066bfa

importutils: removing occurrences of pynames in from imports

Added ImportedModule.remove_imports() and RemovePyNameVisitor

Comments (0)

Files changed (3)


 import rope.base.evaluate
 from rope.base.change import ChangeSet, ChangeContents
 from rope.refactor import occurrences, rename
-from rope.refactor.importutils import module_imports
+from rope.refactor.importutils import module_imports, actions
 from rope.refactor.importutils.importinfo import NormalImport, FromImport
 import rope.base.codeanalyze


 import sys
 from rope.base import pyobjects, exceptions
+from rope.refactor import occurrences
 from rope.refactor.importutils import importinfo
                ('.' in name and len(name) > self.maxlength)
+class RemovePyNameVisitor(ImportInfoVisitor):
+    def __init__(self, pycore, pymodule, pyname, folder):
+        self.pymodule = pymodule
+        self.pyname = pyname
+        self.context = importinfo.ImportContext(pycore, folder)
+    def visitFromImport(self, import_stmt, import_info):
+        new_pairs = []
+        if not import_info.is_star_import():
+            for name, alias in import_info.names_and_aliases:
+                try:
+                    pyname = self.pymodule[alias or name]
+                    if occurrences.same_pyname(self.pyname, pyname):
+                        continue
+                except exceptions.AttributeNotFoundError:
+                    pass
+                new_pairs.append((name, alias))
+        return importinfo.FromImport(
+            import_info.module_name, import_info.level, new_pairs)
+    def dispatch(self, import_):
+        result = ImportInfoVisitor.dispatch(self, import_)
+        if result is not None:
+            import_.import_info = result
 def _is_future(info):
     return isinstance(info, importinfo.FromImport) and \
            info.module_name == '__future__'


         return visitor.to_be_renamed
+    def remove_pyname(self, pyname):
+        """Removes pyname when imported in ``from mod import x``"""
+        visitor = actions.RemovePyNameVisitor(self.pycore, self.pymodule,
+                                              pyname, self._current_folder())
+        for import_stmt in self.imports:
+            import_stmt.accept(visitor)
 class _OneTimeSelector(object):
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.