Skip to content

Commit

Permalink
Show an error if the class has non-annotated attributes and we want t…
Browse files Browse the repository at this point in the history
…o convert it to a Mojo struct
  • Loading branch information
msaelices committed Sep 15, 2023
1 parent 1dc2d0d commit 94dabd0
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
5 changes: 5 additions & 0 deletions py2mojo/converters/classdef.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

from tokenize_rt import Token

from ..exceptions import ParseException
from ..helpers import ast_to_offset, find_token
from ..rules import RuleSet

Expand All @@ -16,6 +17,10 @@ def _replace_class_keyword(tokens: list, i: int, rules: RuleSet) -> None:
def convert_classdef(node: ast.FunctionDef, rules: RuleSet) -> Iterable:
"""Converts the annotation of the given function definition."""
if rules.convert_class_to_struct:
for child in node.body:
if isinstance(child, ast.Assign):
raise ParseException(node, 'Class contains non type annotated attributes.')

offset = ast_to_offset(node)
yield (
offset,
Expand Down
17 changes: 17 additions & 0 deletions tests/test_classdef.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import pytest

from helpers import validate
from py2mojo.exceptions import ParseException
from py2mojo.rules import RuleSet


Expand All @@ -12,3 +15,17 @@ def test_classdef():
'struct Foo(Bar): pass',
rules=RuleSet(convert_class_to_struct=True),
)


def test_classdef_non_fully_annotated_functions():
validate(
'''class Number: number = 10''',
'''class Number: number = 10''',
rules=RuleSet(convert_class_to_struct=False),
)
with pytest.raises(ParseException):
validate(
'''class Number: number = 10''',
'''class Number: number = 10''',
rules=RuleSet(convert_class_to_struct=True),
)

0 comments on commit 94dabd0

Please sign in to comment.