def _handle_import_from(self, statement, interesting_klass): self.add_imported_symbol(statement) if interesting_klass in [name.name for name in statement.names]: self.interesting_klass_found = True if statement.module != self.module: return name = get_statement_import_as(statement).get(self.klass, None) if name is not None: self.klass_imports.add(name)
def _handle_import(self, statement): self.add_imported_symbol(statement) imported_as = get_statement_import_as(statement) name = imported_as.get(self.module, None) if name is not None: self.mod_imports.add(name) for as_name in imported_as.values(): for mod_name in self._all_module_level_names(as_name): if mod_name == self.module: self.mod_imports.add(mod_name)
def get_symbol_module_path_from_statement(statement, name_index=0): symbol = "" module_path = "" module_alias = "" symbol_alias = "" import_as = get_statement_import_as(statement) names = list(import_as.keys()) as_names = list(import_as.values()) if isinstance(statement, ast.Import): # On an Import statement, it's impossible to import a symbol # so everything is the module_path module_path = names[name_index] module_alias = as_names[name_index] elif isinstance(statement, ast.ImportFrom): symbol = names[name_index] relative = ImportedSymbol._get_relative_prefix(statement) module_name = statement.module or "" module_path = relative + module_name symbol_alias = as_names[name_index] return symbol, module_path, module_alias, symbol_alias
def test_import(self): statement = ast.parse("import os").body[0] self.assertEqual({"os": "os"}, get_statement_import_as(statement))
def test_incorrect_statement_type(self): statement = ast.parse("pass").body[0] with self.assertRaises(ValueError): _ = get_statement_import_as(statement)
def test_import_order(self): statement = ast.parse("import z, a").body[0] self.assertEqual(collections.OrderedDict({"z": "z", "a": "a"}), get_statement_import_as(statement))
def test_import_from_alias(self): statement = ast.parse("from os import path as stdlibpath").body[0] self.assertEqual({"path": "stdlibpath"}, get_statement_import_as(statement))
def test_import_alias(self): statement = ast.parse("import os as operatingsystem").body[0] self.assertEqual({"os": "operatingsystem"}, get_statement_import_as(statement))