Handle syntax error in find_imports (#1819)

This commit is contained in:
Hood Chatham 2021-09-07 09:42:51 -07:00 committed by GitHub
parent ee1d9199d2
commit de781fdc26
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 27 additions and 9 deletions

View File

@ -57,6 +57,10 @@ substitutions:
- {{Fix}} Fixed a use after free bug in the error handling code. - {{Fix}} Fixed a use after free bug in the error handling code.
{pr}`1816` {pr}`1816`
- {{Enhancement}} If `find_imports` is used on code that contains a syntax
error, it will return an empty list instead of raising a `SyntaxError`.
{pr}`1819`
## Version 0.18.0 ## Version 0.18.0
_August 3rd, 2021_ _August 3rd, 2021_

View File

@ -515,7 +515,8 @@ def find_imports(source: str) -> List[str]:
Returns Returns
------- -------
``List[str]`` ``List[str]``
A list of module names that are imported in ``source``. A list of module names that are imported in ``source``. If ``source`` is not
syntactically correct Python code (after dedenting), returns an empty list.
Examples Examples
-------- --------
@ -527,7 +528,10 @@ def find_imports(source: str) -> List[str]:
# handle mis-indented input from multi-line strings # handle mis-indented input from multi-line strings
source = dedent(source) source = dedent(source)
mod = ast.parse(source) try:
mod = ast.parse(source)
except SyntaxError:
return []
imports = set() imports = set()
for node in ast.walk(mod): for node in ast.walk(mod):
if isinstance(node, ast.Import): if isinstance(node, ast.Import):

View File

@ -11,16 +11,26 @@ from pyodide import find_imports, eval_code, CodeRunner, should_quiet # noqa: E
def test_find_imports(): def test_find_imports():
res = find_imports( res = find_imports(
dedent( """
""" import numpy as np
import numpy as np from scipy import sparse
from scipy import sparse import matplotlib.pyplot as plt
import matplotlib.pyplot as plt """
"""
)
) )
assert set(res) == {"numpy", "scipy", "matplotlib"} assert set(res) == {"numpy", "scipy", "matplotlib"}
# If there is a syntax error in the code, find_imports should return empty
# list.
res = find_imports(
"""
import numpy as np
from scipy import sparse
import matplotlib.pyplot as plt
for x in [1,2,3]
"""
)
assert res == []
def test_code_runner(): def test_code_runner():
assert should_quiet("1+1;") assert should_quiet("1+1;")