diff --git a/src/safeds_stubgen/stubs_generator/_generate_stubs.py b/src/safeds_stubgen/stubs_generator/_generate_stubs.py index 42e83db8..9ee6ba20 100644 --- a/src/safeds_stubgen/stubs_generator/_generate_stubs.py +++ b/src/safeds_stubgen/stubs_generator/_generate_stubs.py @@ -415,17 +415,26 @@ def _create_type_string(self, type_data: dict | None) -> str: return f"{name}<{', '.join(types)}>" return f"{name}" 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": diff --git a/tests/data/test_stub_generation/function_module.py b/tests/data/test_stub_generation/function_module.py index 09fd0e85..e04e48cd 100644 --- a/tests/data/test_stub_generation/function_module.py +++ b/tests/data/test_stub_generation/function_module.py @@ -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, ): ... diff --git a/tests/safeds_stubgen/stubs_generator/test_generate_stubs.py b/tests/safeds_stubgen/stubs_generator/test_generate_stubs.py index fa23d49d..7275b419 100644 --- a/tests/safeds_stubgen/stubs_generator/test_generate_stubs.py +++ b/tests/safeds_stubgen/stubs_generator/test_generate_stubs.py @@ -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()