Can I omit Optional if I set default to None?

后端 未结 2 738
有刺的猬
有刺的猬 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:20

    A previous version of the standard, as defined in PEP 484 allowed for this.

    However, the most up to date version states the following in the Union section:

    A past version of this PEP allowed type checkers to assume an optional type when the default value is None, as in this code:

    def handle_employee(e: Employee = None): ...
    

    This would have been treated as equivalent to:

    def handle_employee(e: Optional[Employee] = None) -> None: ...
    

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

    I'm glad about this. To my eyes, it actually looks jarring.

提交回复
热议问题