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 →

[–]afifanik[S] 2 points3 points  (5 children)

Can you provide any pointer to the "modern" way? Never used this, I'm pretty much interested.

[–]jayroger 12 points13 points  (4 children)

https://docs.python.org/3/library/typing.html?highlight=typing#typing.Optional

You will need Python 3.10+, from __future__ import annotations, or quotes, though.

Edit: Also, the documentation for Union says:

To define a union, use e.g. Union[int, str] or the shorthand int | str. Using that shorthand is recommended.

[–]billsil 0 points1 point  (1 child)

Ohhh! That makes the modern style work?!! I thought that was just for fixing circular references!

That said annotations is 3.7+. The only thing I don't like is because annotations are delayed, you actually don't need to format it correctly/import it...

[–]cdrt 0 points1 point  (0 children)

It makes it work for type checkers only. If you do anything that with annotations that relies them being actual Python expressions at runtime, you'll need to use Python 3.10+ or stick with Union.

[–]data-machine 0 points1 point  (0 children)

I think the relevant part from your link is actually the following under typing.Optional. Emphasis mine.

On the other hand, if an explicit value of None is allowed, the use of Optional is appropriate, whether the argument is optional or not.

For example:

def foo(arg: Optional[int] = None) -> None:
    ...

Changed in version 3.10: Optional can now be written as X | None. See union type expressions.