Can we use `bool or None` instead of Union[bool, None] for type annotating?

737 Views Asked by At

I'm using python3.8 and have a variable which can be True, False or None. For type-hinting this variable I know I can use Union for variables where they may have divergent types. But personally I don't prefer using Union. I think it's easier to use the newer python syntax bool | None but it's not available in python3.8 (I think it's for 3.9 or 3.10). I want to know is it correct to use bool or None for this scenario? At first I thought it's wrong, because bool or None will be eventually executed and become bool.

>>> bool or None
<class 'bool'>

But pycharm's type checker didn't complain about it. Is this correct?

2

There are 2 best solutions below

1
smnenko On

You've answered on your issue youself.

bool or None  # returns bool type
bool | None  # just equal to Union[bool, None] for Python 3.10+ 
             # and provides cleanest syntax for Type Hinting

Sure you can't use this in Python 3.9 or lower, because this structure (bitwise or) is not implemented. If you exactly wants to use type hints in Python 3.8, you have to use typing.Union

3
knia On

@smnenko's answer is correct, but even in Python 3.10 you can also do

from typing import Optional

x: Optional[bool]

Optional[T] is the same as Union[T, None].