1

How can I combine the following:

def function(arg1, arg2: str):...

and

def function(arg1, arg2={}):...

?

In the first case, I NEED to enter two arguments. But it can be possible, that arg2 is not given to the function (-> error). I would like to have the second option but additionally with : str, so that I HAVE to give a string as arg2 to the function IF I like to use arg2.

I tried something like

def function(arg1, arg2={}: str):...

but it did not work. Of course, there is the possibility to check the type inside of the function, that is clear and throw an exception. That is clear. To have a compact solution as with arg: <type> in the function call is elegant.

Anton Menshov
  • 2,266
  • 14
  • 34
  • 55
Markus
  • 101
  • 1
  • 7
  • 2
    This question is answered [here](https://stackoverflow.com/questions/38727520/adding-default-parameter-value-with-type-hint-in-python). – Ajay Dabas Jan 10 '20 at 10:23
  • 7
    Why is the default parameter a dictionary if its supposed to be a string? – Sayse Jan 10 '20 at 10:24
  • If you need something like this, then I guess you should rethink what you want to do with your function – Eternal Jan 10 '20 at 10:33
  • 1
    Using `arg2={}` is not a good idea. See [“Least Astonishment” and the Mutable Default Argument](https://stackoverflow.com/q/1132941/3929826) for details! – Klaus D. Jan 10 '20 at 10:40
  • "... with ": str", so that I HAVE to give a string ..." Type hints in Python are not enforced by the language runtime, mostly just a friendly reminder to programmers and tools like IDEs about what types should be passed – Hymns For Disco Jan 10 '20 at 12:13

0 Answers0