Skip to content

Commit

Permalink
Fixed create type function for stubs generator for None types in Unions
Browse files Browse the repository at this point in the history
  • Loading branch information
Masara committed Nov 14, 2023
1 parent 35f0dd1 commit 164a416
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 6 deletions.
19 changes: 14 additions & 5 deletions src/safeds_stubgen/stubs_generator/_generate_stubs.py
Original file line number Diff line number Diff line change
Expand Up @@ -415,17 +415,26 @@ def _create_type_string(self, type_data: dict | None) -> str:
return f"{name}<{', '.join(types)}>"
return f"{name}<Any>"
elif kind == "UnionType":
types = [
# Union items have to be unique
types = list({
self._create_type_string(type_)
for type_ in type_data["types"]
]
})

if types:
if len(types) == 2 and none_type_name in types:
if types[0] == none_type_name:
# if None is one of the two possible types, we can remove the None and just return the other
# type with a question mark
if types[0] == types[1] == none_type_name:
return none_type_name
elif types[0] == none_type_name:
return f"{types[1]}?"
else:
return f"{types[0]}?"
return f"{types[0]}?"

# If the union contains only one type, return the type instead of creating an union
elif len(types) == 1:
return types[0]

return f"union<{', '.join(types)}>"
return ""
elif kind == "TupleType":
Expand Down
7 changes: 6 additions & 1 deletion tests/data/test_stub_generation/function_module.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,13 @@ def illegal_params(


def special_params(
none_bool_union: None | bool,
none_union: None | None,
none_bool_union: None | bool,
bool_none_union: bool | None,
none_bool_none_union: None | bool | None,
none_bool_int_union: None | bool | int,
none_none_bool_none_union: None | None | bool | None,
none_list_union_none_none: None | list[None | None] | None,
none: None,
): ...

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
stubs_generator.generate_stubs()


# Todo Frage: Automatische Einrückung bei .ambr Dateien -> Snapshot Test schlagen deswegen fehl
# Utilites
def _assert_file_creation_recursive(python_path: Path, stub_path: Path) -> None:
assert python_path.is_dir()
Expand Down

0 comments on commit 164a416

Please sign in to comment.