How can I annotate a type that can be anything but None
? In other words, this type is Any
but is not None
.
Asked
Active
Viewed 1,393 times
8

xuhdev
- 8,018
- 2
- 41
- 69
-
3You can't. There's no way to express that. – user2357112 Nov 04 '20 at 23:19
-
1Interesting question, do you have a specific use case in mind where "give me anything you want, as long as it is not exactly `None`" is a useful requirement? – Niklas Mertsch Nov 04 '20 at 23:28
-
@NiklasMertsch Imagine a function that takes in a file path, and determines the nature of the file, and returns a proper objects that represent the content of the file (e.g., `str` if it determines the file is plain text and `PIL.Image` if it determines the files is an image, and `bytes` if it's anything else). Further imagine that the function is in a package that allows user to register their own type determiner and handler. And the design decides that the return type can't be None. Then the return type can be virtually anything but None. – xuhdev Nov 04 '20 at 23:45
-
1I see, but why would you want type annotations on such a thing? And what's the actual real-life benefit of a `AllExcept[None]` over `Any`? Should a user not be allowed to register a handler that can result in `None`? In my opinion this would be the perfect example of a good place for `Any`. – Niklas Mertsch Nov 05 '20 at 01:00
-
@NiklasMertsch That's the point: A user must not register a handler that can result in `None`. How much the benefit of an `AllExcept[None]` offers is somewhat subjective, I think. One may argue it really doesn't bring anything, but one can also argue it clarifies what the function might do a bit better. – xuhdev Nov 05 '20 at 01:07
1 Answers
-2
You can do Union[int, str, ...]
but exclude None
from that union.

Flair
- 2,609
- 1
- 29
- 41
-
3
-
@xuhdev if the return type cannot be `None`, then the return type would not be `Any`. – Flair Nov 05 '20 at 00:51
-
-
-
-
https://docs.python.org/3/library/typing.html#typing.Type Also feel free to create a feature enhancement request for this in https://bugs.python.org/ if you feel that this kind of data type is common. – Flair Nov 05 '20 at 01:21
-
1@Flair -- typing.Type isn't something that lets you create a type. Rather, it's a way to express the type of a type. For example, if we do `var1 = 3`, the type of `var1` is "int". But what if we do `var2 = int` -- what's the type of `var2`? In this case, it would be "typing.Type[int]". – Michael0x2a Nov 05 '20 at 18:55
-
I was suggesting to create your own type, and as shown in the docs, you would annotate with your own type. I was not suggesting that `typing.Type` would create your type for you; that would be outside of the scope of type notation. – Flair Nov 05 '20 at 19:00