Python 3 type hinting for None?

后端 未结 3 760
-上瘾入骨i
-上瘾入骨i 2021-01-01 08:59
def foo(
        hello: str=\'world\', bar: str=None,
        another_string_or_None: str|????=None):
    pass

I\'m trying to set a type hint in Py

3条回答
  •  醉酒成梦
    2021-01-01 09:19

    It's just None!

    >>> def nothing(nun: None) -> None:
    ...     return nun
    ... 
    >>> nothing(None)
    >>> 
    

    Or at least, it can be.

    Since these annotations are meaningless to Python beyond being in/correct syntax, it's sort of up to the tools.

    If you use typecheck-decorator for example, then you'll need to use type(None):

    >>> import typecheck as tc
    >>>
    >>> @tc.typecheck
    >>> def nothing(nun: type(None)) -> type(None):
    ...     return nun
    ... 
    >>> nothing(None)
    >>> nothing(0)
    typecheck.framework.InputParameterError: nothing() has got an incompatible value for nun: 0
    >>> nothing(False)
    typecheck.framework.InputParameterError: nothing() has got an incompatible value for nun: False
    

    Typecheck also allows you to somewhat more clearly "add more than one type hint with" with tc.any() (OR), tc.all() (AND), and far more besides.

    Beware that tc.none() is a NAND-like predicate; not what you are looking for - with no arguments it will accept any type, equivalent to tc.all() or the more apt tc.anything.

提交回复
热议问题