How do I get Pylance to ignore the possibility of None?

There are many ways of forcing a type-checker to accept this.


  1. Use assert:

    from typing import Union
    
    def do_something(var: Union[T, None]):
        assert var is not None
        var.foo()
    

  2. Raise some other exception:

    from typing import Union
    
    def do_something(var: Union[T, None]):
        if var is None:
            raise RuntimeError("NO")
        var.foo()
    

  3. Use an if statement:

    from typing import Union
    
    def do_something(var: Union[T, None]):
        if var is not None:
            var.foo()
    

  4. Use typing.cast, a function that does nothing at runtime but forces a type-checker to accept that a variable is of a certain type:

    from typing import Union, cast
    
    def do_something(var: Union[T, None]):
        var = cast(T, var)
        var.foo()
    

  5. Switch off the type-checker for that line:

    from typing import Union
    
    def do_something(var: Union[T, None]):
        var.foo()  # type: ignore
    


Note also that, while it makes no difference to how your type annotation is interpreted by a type-checker (the two are semantically identical), you can also write typing.Union[T, None] as typing.Optional[T], which is arguably slightly nicer syntax. In Python >=3.10 (or earlier if you have from __future__ import annotations at the top of your code), you can even write Union types with the | operator, i.e. T | None.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)