Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add default parameters to functions when using type hinting?

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 
like image 423
josh Avatar asked Aug 02 '16 18:08

josh


People also ask

What rules apply for functions with default parameters?

Rule 1: creating functions. When programmers give a parameter a default value, they must give default values to all the parameters to right of it in the parameter list.

Can you assign the default values to a function parameters in PHP?

PHP allows us to set default argument values for function parameters. If we do not pass any argument for a parameter with default value then PHP will use the default set value for this parameter in the function call.

Which of the following function types of function Cannot have default parameters?

Constructors cannot have default parameters.


2 Answers

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.

like image 95
noɥʇʎԀʎzɐɹƆ Avatar answered Sep 21 '22 23:09

noɥʇʎԀʎzɐɹƆ


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:     ... 
like image 24
Tomasz Bartkowiak Avatar answered Sep 20 '22 23:09

Tomasz Bartkowiak