File tree 2 files changed +21
-8
lines changed 2 files changed +21
-8
lines changed Original file line number Diff line number Diff line change @@ -98,17 +98,17 @@ def constants_from_module(module: ModuleType) -> AbstractSet[ConstantT]:
98
98
try :
99
99
source = inspect .getsource (module )
100
100
tree = ast .parse (source )
101
+ visitor = ConstantVisitor ()
102
+ visitor .visit (tree )
101
103
except Exception :
104
+ # A bunch of things can go wrong here.
105
+ # * `module` may have a missing or wrong source location
106
+ # * ast.parse may fail on the source code
107
+ # * NodeVisitor may hit a RecursionError (see many related issues on
108
+ # e.g. libcst https://github.com/Instagram/LibCST/issues?q=recursion),
109
+ # or a MemoryError (`"[1, " * 200 + "]" * 200`)
102
110
return set ()
103
111
104
- visitor = ConstantVisitor ()
105
- try :
106
- visitor .visit (tree )
107
- except RecursionError : # pragma: no cover
108
- # NodeVisitor has a recursive structure, and so deeply nested expressions
109
- # can hit the recursion limit. See the many related issues on e.g. libcst:
110
- # https://github.com/Instagram/LibCST/issues?q=recursion
111
- pass
112
112
return visitor .constants
113
113
114
114
Original file line number Diff line number Diff line change 9
9
# obtain one at https://mozilla.org/MPL/2.0/.
10
10
11
11
import ast
12
+ import inspect
12
13
import subprocess
13
14
import sys
14
15
import textwrap
@@ -190,3 +191,15 @@ def test_constants_from_bad_module():
190
191
)
191
192
def test_local_modules_ignores_test_modules (path ):
192
193
assert not _is_local_module_file (path )
194
+
195
+
196
+ def test_ignores_ast_parse_error (tmp_path ):
197
+ p = tmp_path / "errors_on_parse.py"
198
+ p .write_text ("[1, " * 200 + "]" * 200 )
199
+ module = ModuleType ("<test_constants_from_module_large_string>" )
200
+ module .__file__ = str (p )
201
+
202
+ with pytest .raises (MemoryError ):
203
+ ast .parse (inspect .getsource (module ))
204
+
205
+ assert constants_from_module (module ) == set ()
You can’t perform that action at this time.
0 commit comments