Skip to content

Commit df0dec5

Browse files
committed
Complete canonical inspect and types closure for importlib metadata
Refresh whole canonical inspect/types production and related test families through update_lib after hosted CI exposed stale __cached__ consumers. Add coroutine and async-generator state getters, with closed-state priority for reentrant frame-local finalizers, and expose the existing frame-locals proxy type with its CPython class documentation. Preserve the optional _datetime and unittest import blocks through a narrow migration adapter. Retain canonical assertions and existing guards; record the missing LazyImportType expectation before adding a conditional expected failure, and capability-skip only the two absent-_testcapi CLI fixtures. Assisted-by: OpenAI Codex:model version unavailable
1 parent 3c4989e commit df0dec5

14 files changed

Lines changed: 874 additions & 120 deletions

File tree

‎Lib/inspect.py‎

Lines changed: 151 additions & 65 deletions
Original file line numberDiff line numberDiff line change
@@ -153,19 +153,19 @@
153153
import itertools
154154
import linecache
155155
import os
156-
import re
156+
lazy import re
157157
import sys
158-
import tokenize
158+
lazy import tokenize
159159
import token
160160
import types
161161
import functools
162162
import builtins
163163
from keyword import iskeyword
164164
from operator import attrgetter
165165
from collections import namedtuple, OrderedDict
166-
from weakref import ref as make_weakref
166+
from _weakref import ref as make_weakref
167167

168-
# Create constants for the compiler flags in Include/code.h
168+
# Create constants for the compiler flags in Include/cpython/code.h
169169
# We try to get them from dis to avoid duplication
170170
mod_dict = globals()
171171
for k, v in dis.COMPILER_FLAG_NAMES.items():
@@ -421,7 +421,6 @@ def iscode(object):
421421
co_freevars tuple of names of free variables
422422
co_posonlyargcount number of positional only arguments
423423
co_kwonlyargcount number of keyword only arguments (not including ** arg)
424-
co_lnotab encoded mapping of line numbers to bytecode indices
425424
co_name name with which this code object was defined
426425
co_names tuple of names other than arguments and function locals
427426
co_nlocals number of local variables
@@ -712,8 +711,8 @@ def _findclass(func):
712711
return None
713712
return cls
714713

715-
def _finddoc(obj):
716-
if isclass(obj):
714+
def _finddoc(obj, *, search_in_class=True):
715+
if search_in_class and isclass(obj):
717716
for base in obj.__mro__:
718717
if base is not object:
719718
try:
@@ -753,6 +752,12 @@ def _finddoc(obj):
753752
cls = _findclass(obj.fget)
754753
if cls is None or getattr(cls, name) is not obj:
755754
return None
755+
# Should be tested before ismethoddescriptor()
756+
elif isinstance(obj, functools.cached_property):
757+
name = obj.attrname
758+
cls = _findclass(obj.func)
759+
if cls is None or getattr(cls, name) is not obj:
760+
return None
756761
elif ismethoddescriptor(obj) or isdatadescriptor(obj):
757762
name = obj.__name__
758763
cls = obj.__objclass__
@@ -773,19 +778,37 @@ def _finddoc(obj):
773778
return doc
774779
return None
775780

776-
def getdoc(object):
781+
def _getowndoc(obj):
782+
"""Get the documentation string for an object if it is not
783+
inherited from its class."""
784+
try:
785+
doc = object.__getattribute__(obj, '__doc__')
786+
if doc is None:
787+
return None
788+
if obj is not type:
789+
typedoc = type(obj).__doc__
790+
if isinstance(typedoc, str) and typedoc == doc:
791+
return None
792+
return doc
793+
except AttributeError:
794+
return None
795+
796+
def getdoc(object, *, fallback_to_class_doc=True, inherit_class_doc=True):
777797
"""Get the documentation string for an object.
778798
779799
All tabs are expanded to spaces. To clean up docstrings that are
780800
indented to line up with blocks of code, any whitespace than can be
781801
uniformly removed from the second line onwards is removed."""
782-
try:
783-
doc = object.__doc__
784-
except AttributeError:
785-
return None
802+
if fallback_to_class_doc:
803+
try:
804+
doc = object.__doc__
805+
except AttributeError:
806+
return None
807+
else:
808+
doc = _getowndoc(object)
786809
if doc is None:
787810
try:
788-
doc = _finddoc(object)
811+
doc = _finddoc(object, search_in_class=inherit_class_doc)
789812
except (AttributeError, TypeError):
790813
return None
791814
if not isinstance(doc, str):
@@ -1236,18 +1259,20 @@ def getargs(co):
12361259
FullArgSpec = namedtuple('FullArgSpec',
12371260
'args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations')
12381261

1239-
def getfullargspec(func):
1262+
def getfullargspec(func, *, annotation_format=Format.VALUE):
12401263
"""Get the names and default values of a callable object's parameters.
12411264
1242-
A tuple of seven things is returned:
1243-
(args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations).
1265+
A FullArgSpec namedtuple is returned, which has the following attributes:
12441266
'args' is a list of the parameter names.
12451267
'varargs' and 'varkw' are the names of the * and ** parameters or None.
12461268
'defaults' is an n-tuple of the default values of the last n parameters.
12471269
'kwonlyargs' is a list of keyword-only parameter names.
12481270
'kwonlydefaults' is a dictionary mapping names from kwonlyargs to defaults.
12491271
'annotations' is a dictionary mapping parameter names to annotations.
12501272
1273+
The *annotation_format* parameter controls the format of the annotations.
1274+
See the annotationlib documentation for details.
1275+
12511276
Notable differences from inspect.signature():
12521277
- the "self" parameter is always reported, even for bound methods
12531278
- wrapper chains defined by __wrapped__ *not* unwrapped automatically
@@ -1273,7 +1298,8 @@ def getfullargspec(func):
12731298
follow_wrapper_chains=False,
12741299
skip_bound_arg=False,
12751300
sigcls=Signature,
1276-
eval_str=False)
1301+
eval_str=False,
1302+
annotation_format=annotation_format)
12771303
except Exception as ex:
12781304
# Most of the times 'signature' will raise ValueError.
12791305
# But, it can also raise AttributeError, and, maybe something
@@ -1615,7 +1641,6 @@ def getframeinfo(frame, context=1):
16151641

16161642
def getlineno(frame):
16171643
"""Get the line number from a frame object, allowing for optimization."""
1618-
# FrameType.f_lineno is now a descriptor that grovels co_lnotab
16191644
return frame.f_lineno
16201645

16211646
_FrameInfo = namedtuple('_FrameInfo', ('frame',) + Traceback._fields)
@@ -1709,7 +1734,8 @@ def _shadowed_dict_from_weakref_mro_tuple(*weakref_mro):
17091734
class_dict = dunder_dict['__dict__']
17101735
if not (type(class_dict) is types.GetSetDescriptorType and
17111736
class_dict.__name__ == "__dict__" and
1712-
class_dict.__objclass__ is entry):
1737+
(class_dict.__objclass__ is object or
1738+
class_dict.__objclass__ is entry)):
17131739
return class_dict
17141740
return _sentinel
17151741

@@ -1793,13 +1819,7 @@ def getgeneratorstate(generator):
17931819
GEN_SUSPENDED: Currently suspended at a yield expression.
17941820
GEN_CLOSED: Execution has completed.
17951821
"""
1796-
if generator.gi_running:
1797-
return GEN_RUNNING
1798-
if generator.gi_suspended:
1799-
return GEN_SUSPENDED
1800-
if generator.gi_frame is None:
1801-
return GEN_CLOSED
1802-
return GEN_CREATED
1822+
return generator.gi_state
18031823

18041824

18051825
def getgeneratorlocals(generator):
@@ -1835,13 +1855,7 @@ def getcoroutinestate(coroutine):
18351855
CORO_SUSPENDED: Currently suspended at an await expression.
18361856
CORO_CLOSED: Execution has completed.
18371857
"""
1838-
if coroutine.cr_running:
1839-
return CORO_RUNNING
1840-
if coroutine.cr_suspended:
1841-
return CORO_SUSPENDED
1842-
if coroutine.cr_frame is None:
1843-
return CORO_CLOSED
1844-
return CORO_CREATED
1858+
return coroutine.cr_state
18451859

18461860

18471861
def getcoroutinelocals(coroutine):
@@ -1874,13 +1888,7 @@ def getasyncgenstate(agen):
18741888
AGEN_SUSPENDED: Currently suspended at a yield expression.
18751889
AGEN_CLOSED: Execution has completed.
18761890
"""
1877-
if agen.ag_running:
1878-
return AGEN_RUNNING
1879-
if agen.ag_suspended:
1880-
return AGEN_SUSPENDED
1881-
if agen.ag_frame is None:
1882-
return AGEN_CLOSED
1883-
return AGEN_CREATED
1891+
return agen.ag_state
18841892

18851893

18861894
def getasyncgenlocals(agen):
@@ -2121,7 +2129,6 @@ def _signature_strip_non_python_syntax(signature):
21212129

21222130
current_parameter = 0
21232131
OP = token.OP
2124-
ERRORTOKEN = token.ERRORTOKEN
21252132

21262133
# token stream always starts with ENCODING token, skip it
21272134
t = next(token_stream)
@@ -2198,7 +2205,8 @@ def wrap_value(s):
21982205
except NameError:
21992206
raise ValueError
22002207

2201-
if isinstance(value, (str, int, float, bytes, bool, type(None))):
2208+
if isinstance(value, (str, int, float, bytes, bool, type(None),
2209+
sentinel)):
22022210
return ast.Constant(value)
22032211
raise ValueError
22042212

@@ -3356,22 +3364,113 @@ class BufferFlags(enum.IntFlag):
33563364
WRITE = 0x200
33573365

33583366

3367+
def _get_details_for_cli(module, nominal_target, resolved_target):
3368+
# Determine if the given module name is an alias for another module,
3369+
# or if it is reexporting a name that is actually defined elsewhere
3370+
resolved_module = getmodule(resolved_target)
3371+
if resolved_module is not None and resolved_module is not module:
3372+
# Referenced target indicates it was defined somewhere else,
3373+
# so report the details of that module rather than the lookup module
3374+
module = resolved_module
3375+
reported_module_name = module.__name__
3376+
# Ensure the reported source file reflects the actual defining location
3377+
try:
3378+
source_file = getsourcefile(resolved_target)
3379+
except Exception:
3380+
try:
3381+
source_file = getsourcefile(module)
3382+
except Exception:
3383+
source_file = None
3384+
# Determine if the nominal target location is its defining location
3385+
if resolved_target is module:
3386+
reported_target = reported_module_name
3387+
else:
3388+
reported_qualname = getattr(resolved_target, "__qualname__", None)
3389+
if not reported_qualname:
3390+
reported_qualname = nominal_target.partition(":")[2]
3391+
reported_target = f"{reported_module_name}:{reported_qualname}"
3392+
# Special case for looking up functions in frozen modules
3393+
if source_file == f"<frozen {reported_module_name}>":
3394+
source_file = module.__file__
3395+
# Populate the actual details to be reported
3396+
details = {
3397+
"target": reported_target,
3398+
"origin": module.__spec__.origin,
3399+
"cached": module.__spec__.cached,
3400+
"source": source_file,
3401+
}
3402+
if reported_target != nominal_target:
3403+
details["alias"] = nominal_target
3404+
error = None
3405+
if not source_file:
3406+
if module.__name__ in sys.builtin_module_names:
3407+
error = "No source code available for builtin module"
3408+
else:
3409+
error = "No source code available for defining module"
3410+
if resolved_target is module:
3411+
details["loader"] = repr(module.__spec__.loader)
3412+
if hasattr(module, '__path__'):
3413+
details["submodule_paths"] = str(module.__path__)
3414+
elif source_file:
3415+
try:
3416+
__, lineno = findsource(resolved_target)
3417+
except Exception:
3418+
error = "Failed to retrieve source code for given target"
3419+
else:
3420+
details["lineno"] = lineno
3421+
if error:
3422+
details["error"] = error
3423+
return details
3424+
3425+
def _render_details_for_cli(details):
3426+
resolved_target = details["target"]
3427+
alias = details.get("alias")
3428+
if alias:
3429+
rendered_target = f'{resolved_target} (looked up as "{alias}")'
3430+
else:
3431+
rendered_target = resolved_target
3432+
lines = [
3433+
f'Target: {rendered_target}',
3434+
f'Origin: {details["origin"]}',
3435+
f'Source: {details["source"]}',
3436+
f'Cached: {details["cached"]}',
3437+
]
3438+
loader = details.get("loader")
3439+
if loader:
3440+
lines.append(f'Loader: {loader}')
3441+
submodule_paths = details.get("submodule_paths")
3442+
if submodule_paths:
3443+
lines.append(f'Submodule search paths: {submodule_paths}')
3444+
else:
3445+
error = details.get("error")
3446+
if error:
3447+
# The error is only informational when retrieving object details
3448+
lines.append(error)
3449+
else:
3450+
lines.append(f'Line: {details["lineno"]}')
3451+
3452+
lines.append("")
3453+
return "\n".join(lines)
3454+
3455+
33593456
def _main():
33603457
""" Logic for inspecting an object given at command line """
33613458
import argparse
33623459
import importlib
33633460

3364-
parser = argparse.ArgumentParser(color=True)
3461+
parser = argparse.ArgumentParser()
33653462
parser.add_argument(
33663463
'object',
33673464
help="The object to be analysed. "
3368-
"It supports the 'module:qualname' syntax")
3465+
"It supports the `module:qualname` syntax")
33693466
parser.add_argument(
33703467
'-d', '--details', action='store_true',
33713468
help='Display info about the module rather than its source code')
33723469

33733470
args = parser.parse_args()
33743471

3472+
# We don't use `pkgutil.resolve_name` here because we want to obtain
3473+
# references to both the module *and* the fully resolved target object
33753474
target = args.object
33763475
mod_name, has_attrs, attrs = target.partition(":")
33773476
try:
@@ -3389,29 +3488,16 @@ def _main():
33893488
for part in parts:
33903489
obj = getattr(obj, part)
33913490

3392-
if module.__name__ in sys.builtin_module_names:
3393-
print("Can't get info for builtin modules.", file=sys.stderr)
3394-
sys.exit(1)
3395-
3491+
details = _get_details_for_cli(module, target, obj)
33963492
if args.details:
3397-
print('Target: {}'.format(target))
3398-
print('Origin: {}'.format(getsourcefile(module)))
3399-
print('Cached: {}'.format(module.__cached__))
3400-
if obj is module:
3401-
print('Loader: {}'.format(repr(module.__loader__)))
3402-
if hasattr(module, '__path__'):
3403-
print('Submodule search path: {}'.format(module.__path__))
3404-
else:
3405-
try:
3406-
__, lineno = findsource(obj)
3407-
except Exception:
3408-
pass
3409-
else:
3410-
print('Line: {}'.format(lineno))
3411-
3412-
print('\n')
3493+
print(_render_details_for_cli(details))
34133494
else:
3414-
print(getsource(obj))
3495+
# Attempt to render target source details
3496+
error = details.get("error")
3497+
if error:
3498+
sys.exit(error)
3499+
else:
3500+
print(getsource(obj))
34153501

34163502

34173503
if __name__ == "__main__":

0 commit comments

Comments
 (0)