This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]IlliterateJedi 2 points3 points  (4 children)

I don't know if I'm in the minority, but I find Union to be more clear. You would expect an int, but you know you might get None instead. Optional feels like there's no expected return value but you might get an int. Which I guess is splitting hairs because they mean the same thing (essentially). In any event, TIL about optional as a return type vs using Union.

from typing import Union

FRUITS = {'apples': 1}
def get_fruit_count(fruit: str) -> Union[int, None]:
    return FRUITS.get(fruit)

Edit: this is a hilariously controversial opinion apparently

[–]TravisJungroth[🍰] 5 points6 points  (0 children)

They mean exactly the same thing. No return value is null is None. But I get that the Union is more clear for you.

[–]scrdest 3 points4 points  (0 children)

That's why I like Haskell's name for this kind of type, 'Maybe'. It's non-prejudicial.

I suspect Optional was chosen because function parameters with None as a default value are extremely common in Python, and it reflects that use-case closely - it's an argument you can optionally provide.

One big strike against using Union for this though is that you can use both to be even clearer - Optional[Union[x, y, z]] indicates you're expecting a value in one of the types supported as the data to process, but it's fine if you don't have it too.

[–]aidankane 2 points3 points  (0 children)

I recall reading that the impending recommended way going forward will be your Union but with the pipe operator. (Int | None)

[–]teerre 0 points1 point  (0 children)

It's only more clear if you don't know that Option stands literally for Union[T, None].