Skip to content

Commit bee9051

Browse files
authored
[3.11] gh-85267: Improvements to inspect.signature __text_signature__ handling (GH-98796) (#100392)
This makes a couple related changes to inspect.signature's behaviour when parsing a signature from `__text_signature__`. First, `inspect.signature` is documented as only raising ValueError or TypeError. However, in some cases, we could raise RuntimeError. This PR changes that, thereby fixing GH-83685. (Note that the new ValueErrors in RewriteSymbolics are caught and then reraised with a message) Second, `inspect.signature` could randomly drop parameters that it didn't understand (corresponding to `return None` in the `p` function). This is the core issue in GH-85267. I think this is very surprising behaviour and it seems better to fail outright. Third, adding this new failure broke a couple tests. To fix them (and to e.g. allow `inspect.signature(select.epoll.register)` as in GH-85267), I add constant folding of a couple binary operations to RewriteSymbolics. (There's some discussion of making signature expression evaluation arbitrary powerful in GH-68155. I think that's out of scope. The additional constant folding here is pretty straightforward, useful, and not much of a slippery slope) Fourth, while GH-85267 is incorrect about the cause of the issue, it turns out if you had consecutive newlines in __text_signature__, you'd get `tokenize.TokenError`. Finally, the `if name is invalid:` code path was dead, since `parse_name` never returned `invalid`.. (cherry picked from commit 79311cb) Co-authored-by: Shantanu <12621235+hauntsaninja@users.noreply.github.com>
1 parent fe828ec commit bee9051

File tree

3 files changed

+47
-13
lines changed

3 files changed

+47
-13
lines changed

Lib/inspect.py

+21-12
Original file line numberDiff line numberDiff line change
@@ -2116,7 +2116,7 @@ def _signature_strip_non_python_syntax(signature):
21162116
self_parameter = None
21172117
last_positional_only = None
21182118

2119-
lines = [l.encode('ascii') for l in signature.split('\n')]
2119+
lines = [l.encode('ascii') for l in signature.split('\n') if l]
21202120
generator = iter(lines).__next__
21212121
token_stream = tokenize.tokenize(generator)
21222122

@@ -2192,7 +2192,6 @@ def _signature_fromstr(cls, obj, s, skip_bound_arg=True):
21922192

21932193
parameters = []
21942194
empty = Parameter.empty
2195-
invalid = object()
21962195

21972196
module = None
21982197
module_dict = {}
@@ -2216,11 +2215,11 @@ def wrap_value(s):
22162215
try:
22172216
value = eval(s, sys_module_dict)
22182217
except NameError:
2219-
raise RuntimeError()
2218+
raise ValueError
22202219

22212220
if isinstance(value, (str, int, float, bytes, bool, type(None))):
22222221
return ast.Constant(value)
2223-
raise RuntimeError()
2222+
raise ValueError
22242223

22252224
class RewriteSymbolics(ast.NodeTransformer):
22262225
def visit_Attribute(self, node):
@@ -2230,7 +2229,7 @@ def visit_Attribute(self, node):
22302229
a.append(n.attr)
22312230
n = n.value
22322231
if not isinstance(n, ast.Name):
2233-
raise RuntimeError()
2232+
raise ValueError
22342233
a.append(n.id)
22352234
value = ".".join(reversed(a))
22362235
return wrap_value(value)
@@ -2240,19 +2239,29 @@ def visit_Name(self, node):
22402239
raise ValueError()
22412240
return wrap_value(node.id)
22422241

2242+
def visit_BinOp(self, node):
2243+
# Support constant folding of a couple simple binary operations
2244+
# commonly used to define default values in text signatures
2245+
left = self.visit(node.left)
2246+
right = self.visit(node.right)
2247+
if not isinstance(left, ast.Constant) or not isinstance(right, ast.Constant):
2248+
raise ValueError
2249+
if isinstance(node.op, ast.Add):
2250+
return ast.Constant(left.value + right.value)
2251+
elif isinstance(node.op, ast.Sub):
2252+
return ast.Constant(left.value - right.value)
2253+
elif isinstance(node.op, ast.BitOr):
2254+
return ast.Constant(left.value | right.value)
2255+
raise ValueError
2256+
22432257
def p(name_node, default_node, default=empty):
22442258
name = parse_name(name_node)
2245-
if name is invalid:
2246-
return None
22472259
if default_node and default_node is not _empty:
22482260
try:
22492261
default_node = RewriteSymbolics().visit(default_node)
2250-
o = ast.literal_eval(default_node)
2262+
default = ast.literal_eval(default_node)
22512263
except ValueError:
2252-
o = invalid
2253-
if o is invalid:
2254-
return None
2255-
default = o if o is not invalid else default
2264+
raise ValueError("{!r} builtin has invalid signature".format(obj)) from None
22562265
parameters.append(Parameter(name, kind, default=default, annotation=empty))
22572266

22582267
# non-keyword-only parameters

Lib/test/test_inspect.py

+20-1
Original file line numberDiff line numberDiff line change
@@ -2480,7 +2480,7 @@ def p(name): return signature.parameters[name].default
24802480
self.assertEqual(p('f'), False)
24812481
self.assertEqual(p('local'), 3)
24822482
self.assertEqual(p('sys'), sys.maxsize)
2483-
self.assertNotIn('exp', signature.parameters)
2483+
self.assertEqual(p('exp'), sys.maxsize - 1)
24842484

24852485
test_callable(object)
24862486

@@ -4245,10 +4245,29 @@ def func(*args, **kwargs):
42454245
sig = inspect.signature(func)
42464246
self.assertIsNotNone(sig)
42474247
self.assertEqual(str(sig), '(self, /, a, b=1, *args, c, d=2, **kwargs)')
4248+
42484249
func.__text_signature__ = '($self, a, b=1, /, *args, c, d=2, **kwargs)'
42494250
sig = inspect.signature(func)
42504251
self.assertEqual(str(sig), '(self, a, b=1, /, *args, c, d=2, **kwargs)')
42514252

4253+
func.__text_signature__ = '(self, a=1+2, b=4-3, c=1 | 3 | 16)'
4254+
sig = inspect.signature(func)
4255+
self.assertEqual(str(sig), '(self, a=3, b=1, c=19)')
4256+
4257+
func.__text_signature__ = '(self, a=1,\nb=2,\n\n\n c=3)'
4258+
sig = inspect.signature(func)
4259+
self.assertEqual(str(sig), '(self, a=1, b=2, c=3)')
4260+
4261+
func.__text_signature__ = '(self, x=does_not_exist)'
4262+
with self.assertRaises(ValueError):
4263+
inspect.signature(func)
4264+
func.__text_signature__ = '(self, x=sys, y=inspect)'
4265+
with self.assertRaises(ValueError):
4266+
inspect.signature(func)
4267+
func.__text_signature__ = '(self, 123)'
4268+
with self.assertRaises(ValueError):
4269+
inspect.signature(func)
4270+
42524271
def test_base_class_have_text_signature(self):
42534272
# see issue 43118
42544273
from test.ann_module7 import BufferedReader
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
Several improvements to :func:`inspect.signature`'s handling of ``__text_signature``.
2+
- Fixes a case where :func:`inspect.signature` dropped parameters
3+
- Fixes a case where :func:`inspect.signature` raised :exc:`tokenize.TokenError`
4+
- Allows :func:`inspect.signature` to understand defaults involving binary operations of constants
5+
- :func:`inspect.signature` is documented as only raising :exc:`TypeError` or :exc:`ValueError`, but sometimes raised :exc:`RuntimeError`. These cases now raise :exc:`ValueError`
6+
- Removed a dead code path

0 commit comments

Comments
 (0)