Skip to content

Commit ee3d8dc

Browse files
authored
[3.11] gh-107155: Fix help() for lambda function with return annotation (GH-115613)
(cherry picked from commit b9a9e3d)
1 parent a23aecc commit ee3d8dc

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
@@ -1128,7 +1128,8 @@ def docroutine(self, object, name=None, mod=None,
11281128
# XXX lambda's won't usually have func_annotations['return']
11291129
# since the syntax doesn't support but it is possible.
11301130
# So removing parentheses isn't truly safe.
1131-
argspec = argspec[1:-1] # remove parentheses
1131+
if not object.__annotations__:
1132+
argspec = argspec[1:-1] # remove parentheses
11321133
if not argspec:
11331134
argspec = '(...)'
11341135

@@ -1581,7 +1582,8 @@ def docroutine(self, object, name=None, mod=None, cl=None, homecls=None):
15811582
# XXX lambda's won't usually have func_annotations['return']
15821583
# since the syntax doesn't support but it is possible.
15831584
# So removing parentheses isn't truly safe.
1584-
argspec = argspec[1:-1] # remove parentheses
1585+
if not object.__annotations__:
1586+
argspec = argspec[1:-1] # remove parentheses
15851587
if not argspec:
15861588
argspec = '(...)'
15871589
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)