Adding default parameter value with type hint in Python

后端 未结 3 455
执笔经年
执笔经年 2020-11-28 19:37

If I have a function like this:

def foo(name, opts={}):
  pass

And I want to add type hints to the parameters, how do I do it? The way I as

相关标签:
3条回答
  • 2020-11-28 20:10

    Your second way is correct.

    def foo(opts: dict = {}):
        pass
    
    print(foo.__annotations__)
    

    this outputs

    {'opts': <class 'dict'>}
    

    It's true that's it's not listed in PEP 484, but type hints are an application of function annotations, which are documented in PEP 3107. The syntax section makes it clear that keyword arguments works with function annotations in this way.

    I strongly advise against using mutable keyword arguments. More information here.

    0 讨论(0)
  • 2020-11-28 20:21

    If you're using typing (introduced in Python 3.5) you can use typing.Optional, where Optional[X] is equivalent to Union[X, None]. It is used to signal that the explicit value of None is allowed . From typing.Optional:

    def foo(arg: Optional[int] = None) -> None:
        ...
    
    0 讨论(0)
  • 2020-11-28 20:26

    I recently saw this one-liner:

    def foo(name: str, opts: dict=None) -> str:
        opts = {} if not opts else opts
        pass
    
    0 讨论(0)
提交回复
热议问题