def _get_imported_name(node: ImportFrom, import_path: str) -> Optional[str]: """Resolve the imported name if present.""" if isinstance(node.names, ImportStar): return None *modules, name = import_path.split(".") if not import_from_matches(node, modules): return None for import_alias in node.names: if m.matches(import_alias, m.ImportAlias(name=m.Name(name))): # We're visiting the import statement we're looking for # Get the actual name it's imported as (in case of import alias) imported_name_str = ( import_alias.evaluated_alias or import_alias.evaluated_name ) return imported_name_str return None
def visit_ImportFrom(self, node: ImportFrom) -> Optional[bool]: """Set the `Call` matcher depending on which signals are imported..""" if import_from_matches(node, ["django", "db", "models", "signals"]): for import_alias in node.names: if m.matches(import_alias, self.import_alias_matcher): # We're visiting an import statement for a built-in signal # Get the actual name it's imported as (in case of import alias) imported_name = (import_alias.asname and import_alias.asname.name or import_alias.name) # Add the call matcher for the current signal to the list self.add_disconnect_call_matcher( m.Call(func=m.Attribute( value=m.Name(imported_name.value), attr=m.Name("disconnect"), ), )) return super().visit_ImportFrom(node)
def _check_libary_imported(self, node: ImportFrom) -> bool: """Record matcher if django.template.Library is imported.""" if import_from_matches(node, ["django", "template"]): for import_alias in node.names: if m.matches(import_alias, m.ImportAlias(name=m.Name("Library"))): # We're visiting the `from django.template import Library` statement # Get the actual name it's imported as (in case of import alias) imported_name = ( import_alias.asname and import_alias.asname.name or import_alias.name ) # Build the `Call` matcher to look out for, eg `Library()` self.context.scratch[self.ctx_key_library_call_matcher] = m.Call( func=m.Name(imported_name.value) ) return True return False