josh josh - 7 months ago 32
Python Question

Adding default parameter value with type hint in Python

If I have a function like this:

def foo(name, opts={}):

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:

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:

I can't find anything in the
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:


Your second way is correct.

def foo(opts: dict = {}):


this outputs

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

It's true that's it's not listed in PEP 484, but since 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.