Can I omit Optional if I set default to None?

后端 未结 2 740
有刺的猬
有刺的猬 2021-02-11 17:12

For example:

def foo(bar: int = None):
    pass

When I check a type/annotation of bar pycharm

2条回答
  •  心在旅途
    2021-02-11 17:39

    No. Omitting Optional was previously allowed, but has since been removed.

    A past version of this PEP allowed type checkers to assume an optional type when the default value is None [...]

    This is no longer the recommended behavior. Type checkers should move towards requiring the optional type to be made explicit.

    Some tools may still provide the old behaviour for legacy support. Even if that is the case, do not rely on it being supported in the future.


    In specific, mypy still supports implicit Optional by default, but explicitly notes this may change in the future:

    Optional types and the None type (mypy v0.782)

    [...] You can use the --no-implicit-optional command-line option to stop treating arguments with a None default value as having an implicit Optional[...] type. It’s possible that this will become the default behavior in the future.

    The deprecation of this behaviour is tracked in mypy/#9091

提交回复
热议问题