mirror of https://github.com/pyodide/pyodide.git
Handle syntax error in find_imports (#1819)
This commit is contained in:
parent
ee1d9199d2
commit
de781fdc26
|
@ -57,6 +57,10 @@ substitutions:
|
|||
- {{Fix}} Fixed a use after free bug in the error handling code.
|
||||
{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
|
||||
|
||||
_August 3rd, 2021_
|
||||
|
|
|
@ -515,7 +515,8 @@ def find_imports(source: str) -> List[str]:
|
|||
Returns
|
||||
-------
|
||||
``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
|
||||
--------
|
||||
|
@ -527,7 +528,10 @@ def find_imports(source: str) -> List[str]:
|
|||
# handle mis-indented input from multi-line strings
|
||||
source = dedent(source)
|
||||
|
||||
mod = ast.parse(source)
|
||||
try:
|
||||
mod = ast.parse(source)
|
||||
except SyntaxError:
|
||||
return []
|
||||
imports = set()
|
||||
for node in ast.walk(mod):
|
||||
if isinstance(node, ast.Import):
|
||||
|
|
|
@ -11,16 +11,26 @@ from pyodide import find_imports, eval_code, CodeRunner, should_quiet # noqa: E
|
|||
def test_find_imports():
|
||||
|
||||
res = find_imports(
|
||||
dedent(
|
||||
"""
|
||||
import numpy as np
|
||||
from scipy import sparse
|
||||
import matplotlib.pyplot as plt
|
||||
"""
|
||||
)
|
||||
"""
|
||||
import numpy as np
|
||||
from scipy import sparse
|
||||
import matplotlib.pyplot as plt
|
||||
"""
|
||||
)
|
||||
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():
|
||||
assert should_quiet("1+1;")
|
||||
|
|
Loading…
Reference in New Issue