Skip to content

Commit 79311cb

Browse files
authored
gh-85267: Improvements to inspect.signature __text_signature__ handling (#98796)
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 #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 #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 #85267), I add constant folding of a couple binary operations to RewriteSymbolics. (There's some discussion of making signature expression evaluation arbitrary powerful in #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 #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`.
1 parent c615286 commit 79311cb

File tree

3 files changed

+46
-6
lines changed

3 files changed

+46
-6
lines changed

Lib/inspect.py

+20-5
Original file line numberDiff line numberDiff line change
@@ -2122,7 +2122,7 @@ def _signature_strip_non_python_syntax(signature):
21222122
self_parameter = None
21232123
last_positional_only = None
21242124

2125-
lines = [l.encode('ascii') for l in signature.split('\n')]
2125+
lines = [l.encode('ascii') for l in signature.split('\n') if l]
21262126
generator = iter(lines).__next__
21272127
token_stream = tokenize.tokenize(generator)
21282128

@@ -2221,11 +2221,11 @@ def wrap_value(s):
22212221
try:
22222222
value = eval(s, sys_module_dict)
22232223
except NameError:
2224-
raise RuntimeError()
2224+
raise ValueError
22252225

22262226
if isinstance(value, (str, int, float, bytes, bool, type(None))):
22272227
return ast.Constant(value)
2228-
raise RuntimeError()
2228+
raise ValueError
22292229

22302230
class RewriteSymbolics(ast.NodeTransformer):
22312231
def visit_Attribute(self, node):
@@ -2235,7 +2235,7 @@ def visit_Attribute(self, node):
22352235
a.append(n.attr)
22362236
n = n.value
22372237
if not isinstance(n, ast.Name):
2238-
raise RuntimeError()
2238+
raise ValueError
22392239
a.append(n.id)
22402240
value = ".".join(reversed(a))
22412241
return wrap_value(value)
@@ -2245,14 +2245,29 @@ def visit_Name(self, node):
22452245
raise ValueError()
22462246
return wrap_value(node.id)
22472247

2248+
def visit_BinOp(self, node):
2249+
# Support constant folding of a couple simple binary operations
2250+
# commonly used to define default values in text signatures
2251+
left = self.visit(node.left)
2252+
right = self.visit(node.right)
2253+
if not isinstance(left, ast.Constant) or not isinstance(right, ast.Constant):
2254+
raise ValueError
2255+
if isinstance(node.op, ast.Add):
2256+
return ast.Constant(left.value + right.value)
2257+
elif isinstance(node.op, ast.Sub):
2258+
return ast.Constant(left.value - right.value)
2259+
elif isinstance(node.op, ast.BitOr):
2260+
return ast.Constant(left.value | right.value)
2261+
raise ValueError
2262+
22482263
def p(name_node, default_node, default=empty):
22492264
name = parse_name(name_node)
22502265
if default_node and default_node is not _empty:
22512266
try:
22522267
default_node = RewriteSymbolics().visit(default_node)
22532268
default = ast.literal_eval(default_node)
22542269
except ValueError:
2255-
return None
2270+
raise ValueError("{!r} builtin has invalid signature".format(obj)) from None
22562271
parameters.append(Parameter(name, kind, default=default, annotation=empty))
22572272

22582273
# non-keyword-only parameters

Lib/test/test_inspect.py

+20-1
Original file line numberDiff line numberDiff line change
@@ -2525,7 +2525,7 @@ def p(name): return signature.parameters[name].default
25252525
self.assertEqual(p('f'), False)
25262526
self.assertEqual(p('local'), 3)
25272527
self.assertEqual(p('sys'), sys.maxsize)
2528-
self.assertNotIn('exp', signature.parameters)
2528+
self.assertEqual(p('exp'), sys.maxsize - 1)
25292529

25302530
test_callable(object)
25312531

@@ -4323,10 +4323,29 @@ def func(*args, **kwargs):
43234323
sig = inspect.signature(func)
43244324
self.assertIsNotNone(sig)
43254325
self.assertEqual(str(sig), '(self, /, a, b=1, *args, c, d=2, **kwargs)')
4326+
43264327
func.__text_signature__ = '($self, a, b=1, /, *args, c, d=2, **kwargs)'
43274328
sig = inspect.signature(func)
43284329
self.assertEqual(str(sig), '(self, a, b=1, /, *args, c, d=2, **kwargs)')
43294330

4331+
func.__text_signature__ = '(self, a=1+2, b=4-3, c=1 | 3 | 16)'
4332+
sig = inspect.signature(func)
4333+
self.assertEqual(str(sig), '(self, a=3, b=1, c=19)')
4334+
4335+
func.__text_signature__ = '(self, a=1,\nb=2,\n\n\n c=3)'
4336+
sig = inspect.signature(func)
4337+
self.assertEqual(str(sig), '(self, a=1, b=2, c=3)')
4338+
4339+
func.__text_signature__ = '(self, x=does_not_exist)'
4340+
with self.assertRaises(ValueError):
4341+
inspect.signature(func)
4342+
func.__text_signature__ = '(self, x=sys, y=inspect)'
4343+
with self.assertRaises(ValueError):
4344+
inspect.signature(func)
4345+
func.__text_signature__ = '(self, 123)'
4346+
with self.assertRaises(ValueError):
4347+
inspect.signature(func)
4348+
43304349
def test_base_class_have_text_signature(self):
43314350
# see issue 43118
43324351
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)