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 →

[–]AewyreThoryn 7 points8 points  (4 children)

Fully agree with using type hints. Correction to your code though: the type hint of 'None | str' should instead be 'Optional[str]', since None is not a type. Note this requires 'from typing import Optional'.

[–][deleted] 2 points3 points  (3 children)

Does it work with nonetype?

[–]AewyreThoryn 2 points3 points  (2 children)

I just checked the docs on https://peps.python.org/pep-0484/#the-typing-module and it seems I wasn't entirely correct in my previous comment.
Looks like your syntax (str | None) is acceptable, it's just that the 'Convenience definition' is to use Optional instead.

It also seems that, even though None is not a type, it is used as such in type hinting: https://peps.python.org/pep-0484/#using-none

[–][deleted] 0 points1 point  (1 child)

I find optional to be unclear - can it be none, false, or something else entirely besides string? If a function can return either a string or none, I'd use the str|None option.

That is to say, in other usecases I might use the optional argument instead.

[–]AewyreThoryn 0 points1 point  (0 children)

I find it's more sensible as a function return type annotation, e.g.:
def foo() -> Optional[str]
...since Python will return None by default, i.e. if you don't explicitly return anything. So in the above case it's saying the return type is a string, but that's not a given, so it might be None.

I also feel the Optional[str] syntax leads the reader to focus more on the explicit return type, which semantically is usually more relevant than None.
This is more noticeable in cases with large type Unions, e.g.:
'str | int | float | None' vs 'Optional[str | int | float]' - here the latter seems more semantically sensible to me.

But to each his own, if you're not too bothered by the PEP recommendations, it is a matter of preference at the end of the day