Skip to content

Commit 48ecd41

Browse files
Евгений БлиновЕвгений Блинов
authored andcommitted
Support lambda extraction by AST parsing
1 parent 6073932 commit 48ecd41

4 files changed

Lines changed: 28 additions & 4 deletions

File tree

getsources/clear.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,33 @@
1+
from ast import Lambda, get_source_segment, parse, walk
12
from typing import Any, Callable
23

34
from getsources import getsource
5+
from getsources.errors import UncertaintyWithLambdasError
6+
from getsources.helpers.is_lambda import is_lambda
47

58

69
def getclearsource(function: Callable[..., Any]) -> str:
710
source_code = getsource(function)
811

12+
if is_lambda(function):
13+
stripped_source_code = source_code.strip()
14+
tree = parse(stripped_source_code)
15+
16+
first = True
17+
lambda_node = None
18+
for node in walk(tree):
19+
if isinstance(node, Lambda):
20+
if not first:
21+
raise UncertaintyWithLambdasError('Several lambda functions are defined in a single line of code, can\'t pick the one.')
22+
lambda_node = node
23+
first = False
24+
25+
segment_source = get_source_segment(stripped_source_code, lambda_node)
26+
if segment_source is None:
27+
raise UncertaintyWithLambdasError('It seems that the AST for the lambda function has been modified; can\'t extract the source code.')
28+
return segment_source
29+
30+
931
splitted_source_code = source_code.split('\n')
1032

1133
indent = 0

getsources/errors.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
class UncertaintyWithLambdasError(Exception):
2+
...

getsources/hash.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import hashlib
2+
from ast import Constant, Expr, Lambda, get_source_segment, parse, walk
23
from typing import Any, Callable
3-
from ast import parse, Expr, Constant, Lambda, get_source_segment, walk
44

55
from getsources import getclearsource
66
from getsources.helpers.is_lambda import is_lambda

tests/test_clear.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -49,8 +49,8 @@ def function_2(a, b):
4949
def test_lambda():
5050
function = lambda x: x
5151

52-
assert getclearsource(function) == 'function = lambda x: x'
53-
assert getclearsource(global_function_3) == 'global_function_3 = lambda x: x'
52+
assert getclearsource(function) == 'lambda x: x'
53+
assert getclearsource(global_function_3) == 'lambda x: x'
5454

5555

5656
def test_usual_methods():
@@ -171,4 +171,4 @@ def test_lambda_in_REPL(): # noqa: N802
171171

172172
child.sendline("exit()")
173173

174-
assert any('function = lambda x: x' in x for x in after)
174+
assert any('lambda x: x' in x for x in after)

0 commit comments

Comments
 (0)