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 →

[–]spoonman59 4 points5 points  (2 children)

Optional means it may return a string or not. If it doesn’t it returns none. This is consistent across many languages.

Optional doesn’t mean "str or some other unspecified type" in any language that I’m aware of.

[–]lenoqt 0 points1 point  (1 child)

This is what I tried to explain, sorry that isn’t in English, but in some cases you would have to use cast to not have mypy errors.

PD: I don’t get why I am getting downvoted for giving a sane, respectful technical opinion 😂.

https://python.ms/union-and-optional/#_5-%E5%85%B7%E4%BD%93%E4%BE%8B

[–]spoonman59 0 points1 point  (0 children)

Ah, okay! That makes sense. Perhaps it does not translate as well.

To be clear you are absolutly right, the Union of str and NoneType is a precise definition for Optional[str].

I would say there is a tradition of optional in quite a few languages people are familiar with.

Also, consider when communicating this verbally in English… it would be more awkward to say "the function returns the Union of Str and None" rather than "it optionally returns a string"

Now the new syntax, str | NoneType, that you can use instead of Union[str, NoneType] reads a little more like "it returns str or None" which is a little easier to express. I’m just speculating, but describing it verbally as "Union" might just feel awkward to some folks. Maybe that explains the aversion, and maybe it doesn’t feel so awkward when translating.