Skip to content

Commit d2d812c

Browse files
authored
Add rudimentary support for python files that use type hints. (#56)
1 parent 19f169d commit d2d812c

File tree

3 files changed

+27
-0
lines changed

3 files changed

+27
-0
lines changed

pscript/commonast.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1034,6 +1034,12 @@ def _convert_Assign(self, n):
10341034
def _convert_AugAssign(self, n):
10351035
op = n.op.__class__.__name__
10361036
return AugAssign(self._convert(n.target), op, self._convert(n.value))
1037+
1038+
def _convert_AnnAssign(self, n):
1039+
if n.value is None:
1040+
raise RuntimeError("Cannot convert AnnAssign nodes with no assignment!")
1041+
c = self._convert
1042+
return Assign([c(n.target)], c(n.value))
10371043

10381044
def _convert_Print(self, n): # pragma: no cover - Python 2.x compat
10391045
c = self._convert

pscript/parser1.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -850,6 +850,9 @@ def parse_Import(self, node):
850850
return [] # stuff to help the parser
851851
if node.root == 'time':
852852
return [] # PScript natively supports time() and perf_counter()
853+
if node.root == 'typing':
854+
# User is probably importing type annotations. Ignore this import.
855+
return []
853856
raise JSError('PScript does not support imports.')
854857

855858
def parse_Module(self, node):

pscript/tests/test_commonast.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -379,4 +379,22 @@ def test_python_33_plus():
379379
assert isinstance(node, commonast.YieldFrom)
380380

381381

382+
@skipif(sys.version_info < (3,5), reason='Need Python 3.5+')
383+
def test_annotated_assignments():
384+
# Verify that we treat annotated assignments as regular assingments
385+
code = "foo: int = 3"
386+
node = commonast.parse(code).body_nodes[0]
387+
388+
assert isinstance(node, commonast.Assign)
389+
assert len(node.target_nodes) == 1
390+
assert isinstance(node.target_nodes[0], commonast.Name)
391+
assert node.target_nodes[0].name == "foo"
392+
assert isinstance(node.value_node, commonast.Num)
393+
assert node.value_node.value == 3
394+
395+
# Verify that we do not support annotated assignments with no value
396+
with raises(RuntimeError):
397+
commonast.parse("foo: int")
398+
399+
382400
run_tests_if_main()

0 commit comments

Comments
 (0)