From 8056f71151ed517a53a951bcdf5f942cc3bb3e1d Mon Sep 17 00:00:00 2001 From: Alex Waygood Date: Fri, 24 May 2024 17:02:51 -0400 Subject: [PATCH] Speedup `import inspect` by nearly 50% --- Lib/inspect.py | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/Lib/inspect.py b/Lib/inspect.py index e6e49a4ffa673a..72a14d2530f6f4 100644 --- a/Lib/inspect.py +++ b/Lib/inspect.py @@ -142,7 +142,6 @@ import abc -import ast import dis import collections.abc import enum @@ -150,9 +149,7 @@ import itertools import linecache import os -import re import sys -import tokenize import token import types import functools @@ -160,7 +157,7 @@ from keyword import iskeyword from operator import attrgetter from collections import namedtuple, OrderedDict -from weakref import ref as make_weakref +from _weakref import ref as make_weakref # Create constants for the compiler flags in Include/code.h # We try to get them from dis to avoid duplication @@ -1149,6 +1146,8 @@ def __init__(self): self.body_col0 = None def tokeneater(self, type, token, srowcol, erowcol, line): + import tokenize + if not self.started and not self.indecorator: # skip any decorators if token == "@": @@ -1194,6 +1193,8 @@ def tokeneater(self, type, token, srowcol, erowcol, line): def getblock(lines): """Extract the block of code at the top of the given list of lines.""" blockfinder = BlockFinder() + import tokenize + try: tokens = tokenize.generate_tokens(iter(lines).__next__) for _token in tokens: @@ -1420,6 +1421,7 @@ def formatannotation(annotation, base_module=None): def repl(match): text = match.group() return text.removeprefix('typing.') + import re return re.sub(r'[\w\.]+', repl, repr(annotation)) if isinstance(annotation, types.GenericAlias): return str(annotation) @@ -2155,6 +2157,8 @@ def _signature_strip_non_python_syntax(signature): lines = [l.encode('ascii') for l in signature.split('\n') if l] generator = iter(lines).__next__ + + import tokenize token_stream = tokenize.tokenize(generator) text = [] @@ -2191,10 +2195,10 @@ def _signature_fromstr(cls, obj, s, skip_bound_arg=True): """Private helper to parse content of '__text_signature__' and return a Signature based on it. """ - Parameter = cls._parameter_cls + import ast + Parameter = cls._parameter_cls clean_signature, self_parameter = _signature_strip_non_python_syntax(s) - program = "def foo" + clean_signature + ": pass" try: