Reputation: 10308
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 assumed gives me a syntax error:
def foo(name: str, opts={}: dict) -> str:
pass
The following doesn't throw a syntax error but it doesn't seem like the intuitive way to handle this case:
def foo(name: str, opts: dict={}) -> str:
pass
I can't find anything in the typing
documentation or on a Google search.
Edit: I didn't know how default arguments worked in Python, but for the sake of this question, I will keep the examples above. In general it's much better to do the following:
def foo(name: str, opts: dict=None) -> str:
if not opts:
opts={}
pass
Upvotes: 712
Views: 434281
Reputation: 10637
Your second way is correct.
def foo(opts: dict = {}):
pass
print(foo.__annotations__)
this outputs
{'opts': <class 'dict'>}
Although it is not explicitly mentioned in PEP 484, type hints are a specific use of function annotations, as outlined in PEP 3107. The syntax section clearly demonstrates that keyword arguments can be annotated in this manner.
I strongly advise against using mutable keyword arguments. More information here.
Upvotes: 741
Reputation: 14948
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:
...
With Python 3.10 and above, as mentioned in joel's comment, this can equivalently be written as:
def foo(arg: int | None = None) -> None:
...
Upvotes: 121
Reputation: 487
I recently saw this one-liner:
def foo(name: str, opts: dict=None) -> str:
opts = {} if not opts else opts
pass
Upvotes: 47
Reputation: 1
Correct method
def foo(name: str, opts: dict = {}) -> str:
pass
Type hinting syntax
<name>: <type> = <default_value>
Upvotes: -1