def extract_import_statements_from_function_args_imports_and_assigns( args: ast.arguments, imports: ImportStatementContainer, assigns: AssignmentStatementContainer, current_module_section_path_str: str, ) -> ImportStatementContainer: defaults_dict, annotation_dict = function_args_as_arg_and_annotation_dict( args) # Extract external names. These are the root names (not attrs, the base of attrs) for anything that is not builtin external_names = _unique_external_names_from_default_dict_and_annotation_dict( defaults_dict, annotation_dict) out_imports = ImportStatementContainer([]) # External names may be either due to assignment or due to imports # Handle names due to assignment for name in external_names: if assigns.contains_varname(name): # External name is due to assignment in this module. Create import from this module out_imports.append( ObjectImportStatement.from_str( f'from {current_module_section_path_str} import {name}')) # Handle names which are imported into this file for name in external_names: import_or_none = imports.get_import_for_module_or_obj_name(name) if import_or_none is not None: out_imports.append(import_or_none) # Sanity check, did we find all the imports? n_external = len(external_names) n_imports = len(out_imports) if n_external != n_imports: warnings.warn( f'had {n_external} external names from function definition, only ' f'found {n_imports} imports. May be missing imports') return out_imports
def _combine_imports_get_new_assignments( self, import_assignment_obj, existing_imports: ImportStatementContainer, existing_assigns: AssignmentStatementContainer ) -> ImportsDoubleAssignsTuple: all_imports = existing_imports.copy() new_assigns_begin = AssignmentStatementContainer([]) new_assigns_end = AssignmentStatementContainer([]) possibly_new_imports, possibly_new_assigns = import_assignment_obj.as_imports_and_assignments( ) # Checks to see whether should be added, and whether to beginning or end, then adds [all_imports.add_if_missing(imp) for imp in possibly_new_imports] for assign in possibly_new_assigns: if not existing_assigns.contains_varname(assign.varname): begin = getattr(assign, 'prefer_beginning', False) if begin: new_assigns_begin.append_if_missing(assign) else: new_assigns_end.append_if_missing(assign) return all_imports, new_assigns_begin, new_assigns_end