1

Is there a type hint in the typing module indicating that something can be of any type but None/NoneType?

Like in this hypothetical example:

def foo(bar: AnythingBut[None]):  # does this exist?
    if bar is None:
        raise Exception("bad!")
rypel
  • 4,686
  • 2
  • 25
  • 36
  • 2
    Does this answer your question? [Which type hint expresses that an attribute must not be None?](https://stackoverflow.com/questions/59073717/which-type-hint-expresses-that-an-attribute-must-not-be-none) – Random Davis Dec 29 '20 at 18:24
  • @RandomDavis it _kinda_ does: including `pydantic.validator` was not an option (but could be made one), as my question referenced the `typing` module explicitly. but i get the idea it can't be done just with builtins, unless i'm willing to hardcode everything into `Union[...]`. – rypel Dec 29 '20 at 18:37
  • 2
    Altho this comes pretty close to the linked question, I think the `None` case deserves its own question because it gives too much grief when linter/checker is in strict mode... Also, have been googling something similar for a while now and this question appeared only in SO when I was about to post a dup! – urban Jan 15 '21 at 16:19
  • Also, without being 100% sure, it seems you could used `bar: object` here but might have unwanted [side-effects](https://docs.python.org/3/library/typing.html#the-any-type) – urban Jan 15 '21 at 16:25
  • 1
    @RandomDavis That question asks for a solution using the pydantic library (and the answer provides one), while this answer asks for one in Python's built-in typing library. – user202729 Jan 17 '21 at 06:43
  • On the other hand, the linked question ([Exclude type in Python typing annotation - Stack Overflow](https://stackoverflow.com/questions/57854871/exclude-type-in-python-typing-annotation)) from that question is pretty good. ( tl;dr: there isn't. Just specify it in a docstring or meaningfully-named custom typevar. – user202729 Jan 17 '21 at 06:44
  • There is no way to express "anything other than T", that doesn't really make sense as a type annotation – juanpa.arrivillaga Jan 17 '21 at 07:04

0 Answers0