def load_files_or_qualnames( specifiers: Iterable[str], ) -> Iterable[Union[ModuleType, FunctionInfo]]: fspaths = [] for specifier in specifiers: file_line_match = _FILE_WITH_LINE_RE.match(specifier) if file_line_match: filename, linestr = file_line_match.groups() linenum = int(linestr) fn = load_function_at_line(load_file(filename), filename, linenum) if fn is None: raise ErrorDuringImport(f"") yield fn elif specifier.endswith(".py") or os.path.isdir(specifier): fspaths.append(specifier) else: yield load_by_qualname(specifier) for path in walk_paths(fspaths): yield load_file(path)
def load_function_at_line(entity: Union[ModuleType, type], filename: str, linenum: int) -> Optional[FunctionInfo]: """Load a function or method at a line number.""" module = load_file(filename) for name, member in getmembers(module): if isfunction(member) and _contains_line(member, filename, linenum): return FunctionInfo(entity, name, entity.__dict__[name]) if isclass(member): ctxfn = load_function_at_line(member, filename, linenum) if ctxfn: return ctxfn return None
def pool_worker_process_item( item: WorkItemInput, ) -> Tuple[Counter[str], List[AnalysisMessage]]: filename, options, deadline = item stats: Counter[str] = Counter() options.stats = stats try: module = load_file(filename) except NotFound as e: debug( f'Not analyzing "{filename}" because sub-module import failed: {e}' ) return (stats, []) except ErrorDuringImport as e: debug(f'Not analyzing "{filename}" because import failed: {e}') return (stats, [import_error_msg(e)]) messages = run_checkables(analyze_module(module, options)) return (stats, messages)
def check(args: argparse.Namespace, options: AnalysisOptions, stdout: TextIO) -> int: any_messages = False for name in args.files: entity: object try: entity = load_file(name) if name.endswith('.py') else load_by_qualname(name) except ErrorDuringImport as e: stdout.write(str(short_describe_message(import_error_msg(e))) + '\n') any_messages = True continue debug('Check ', getattr(entity, '__name__', str(entity))) for message in analyze_any(entity, options): line = short_describe_message(message) if line is not None: stdout.write(line + '\n') debug('Traceback for output message:\n', message.traceback) any_messages = True return 2 if any_messages else 0
def test_load_file(self): simplefs(self.root, SIMPLE_FOO) module = load_file(join(self.root, "foo.py")) self.assertNotEqual(module, None) self.assertEqual(module.foofn(5), 6)