0

I am checking the data type of several arguments in a function. If one of them is the wrong type, I want an error to be raised, that says:

TypeError: Argument my_arg did not receive a string!

For instance:

def function(a, b, c, d):
    for arg in [a, b, c, d]:
        if not isinstance(arg, str):
            raise TypeError(f'Argument {"<some arg>"} did not receive a string!')
function(a='djsoa', b='sajdjsld', c='dsaa', d=10)

How can this be done? Please note that using a dict for arguments is not possible for me.

Nicolas Gervais
  • 33,817
  • 13
  • 115
  • 143
  • 1
    Why is it not possible exactly? Would `def function(**kwargs)` counts as "dict for arguments"? – user202729 May 01 '20 at 14:34
  • A value doesn't have an associated name. And the variable the value is assigned to changes too. You can't trace `arg` back to `a`. You will need to use a dict or something comparable *somewhere*. – deceze May 01 '20 at 14:35
  • See the marked duplicate for how to access and inspect the function's arguments. You'll need to change your loop header. Iterate over the parameters; access and check the type of each value. That way, when you hit an error, you'll have the parameter name handy. – Prune May 01 '20 at 14:43
  • I guess I could just zip it with the arg name as a string – Nicolas Gervais May 01 '20 at 14:58

0 Answers0