Skip to content

Commit e32cde5

Browse files
authored
[3.12] gh-107155: Fix help() for lambda function with return annotation (GH-115612)
(cherry picked from commit b9a9e3d)
1 parent 6e89292 commit e32cde5

File tree

3 files changed

+31
-2
lines changed

3 files changed

+31
-2
lines changed

Lib/pydoc.py

+4-2
Original file line numberDiff line numberDiff line change
@@ -1131,7 +1131,8 @@ def docroutine(self, object, name=None, mod=None,
11311131
# XXX lambda's won't usually have func_annotations['return']
11321132
# since the syntax doesn't support but it is possible.
11331133
# So removing parentheses isn't truly safe.
1134-
argspec = argspec[1:-1] # remove parentheses
1134+
if not object.__annotations__:
1135+
argspec = argspec[1:-1] # remove parentheses
11351136
if not argspec:
11361137
argspec = '(...)'
11371138

@@ -1583,7 +1584,8 @@ def docroutine(self, object, name=None, mod=None, cl=None, homecls=None):
15831584
# XXX lambda's won't usually have func_annotations['return']
15841585
# since the syntax doesn't support but it is possible.
15851586
# So removing parentheses isn't truly safe.
1586-
argspec = argspec[1:-1] # remove parentheses
1587+
if not object.__annotations__:
1588+
argspec = argspec[1:-1] # remove parentheses
15871589
if not argspec:
15881590
argspec = '(...)'
15891591
decl = asyncqualifier + title + argspec + note

Lib/test/test_pydoc/test_pydoc.py

+24
Original file line numberDiff line numberDiff line change
@@ -691,6 +691,30 @@ def test_help_output_redirect(self):
691691
finally:
692692
pydoc.getpager = getpager_old
693693

694+
def test_lambda_with_return_annotation(self):
695+
func = lambda a, b, c: 1
696+
func.__annotations__ = {"return": int}
697+
with captured_output('stdout') as help_io:
698+
pydoc.help(func)
699+
helptext = help_io.getvalue()
700+
self.assertIn("lambda (a, b, c) -> int", helptext)
701+
702+
def test_lambda_without_return_annotation(self):
703+
func = lambda a, b, c: 1
704+
func.__annotations__ = {"a": int, "b": int, "c": int}
705+
with captured_output('stdout') as help_io:
706+
pydoc.help(func)
707+
helptext = help_io.getvalue()
708+
self.assertIn("lambda (a: int, b: int, c: int)", helptext)
709+
710+
def test_lambda_with_return_and_params_annotation(self):
711+
func = lambda a, b, c: 1
712+
func.__annotations__ = {"a": int, "b": int, "c": int, "return": int}
713+
with captured_output('stdout') as help_io:
714+
pydoc.help(func)
715+
helptext = help_io.getvalue()
716+
self.assertIn("lambda (a: int, b: int, c: int) -> int", helptext)
717+
694718
def test_namedtuple_fields(self):
695719
Person = namedtuple('Person', ['nickname', 'firstname'])
696720
with captured_stdout() as help_io:
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Fix incorrect output of ``help(x)`` where ``x`` is a :keyword:`lambda`
2+
function, which has an ``__annotations__`` dictionary attribute with a
3+
``"return"`` key.

0 commit comments

Comments
 (0)