0

Function func(*args, **kwargs) should return dictionary, and all elements of that dictionary should be numeric or string variables. If argument of function is dictionary, then function should return dictionary with all elements of argument dictionary, and other arguments. For example:

arg1 = { 'x': 'X', 'y': 'Y' }  
arg2 = 2
arg3 = { 'p': arg1, 'pi': 3.14 }
func(arg2, arg3, arg4=4)

should return this:

{ 'x': 'X', 'y': 'Y', 'arg2': 2, 'pi': 3.14, 'arg4': 4 }

How to do that? Recursion is not desirable.

deceze
  • 510,633
  • 85
  • 743
  • 889
nimi
  • 391
  • 1
  • 2
  • 10
  • 2
    A function `func(*args)` won't be able to determine and return the name `arg2`! – deceze Jun 09 '17 at 07:52
  • Is the p key of arg3 missing ? – Tbaki Jun 09 '17 at 07:55
  • @Tbaki it's not missing, arg3 is dictionary so we have to go deeper and find out if there are numeric or string elements in arg3. – nimi Jun 09 '17 at 08:02
  • @deceze there is locals() function where names of arguments could be determined, am I wrong? – nimi Jun 09 '17 at 08:03
  • No, `locals` won't help you. Only a stack trace would, but please for the love of all that is holy don't go there. – deceze Jun 09 '17 at 08:04
  • OK, i didn't consider that. But what if as *args could be given only dictionaries? – nimi Jun 09 '17 at 08:13
  • Possible duplicate of [What does \*\* (double star/asterisk) and \* (star/asterisk) do for parameters?](https://stackoverflow.com/questions/36901/what-does-double-star-asterisk-and-star-asterisk-do-for-parameters) – Munim Munna Jun 20 '18 at 20:30

2 Answers2

1

When you pass arg2 to the function, the function does not know that it was named arg2 when you passed it in, it just know its value is 2. You would have to get stack trace to know who called that function, scrape source code to get the name and then it would be simple.

But what if I call it like this:

func(2)

what output do you expect then?

0

You could do something like this - but that solution needs argument numbers ascending (arg1, arg2, ..., argN).

def func(*args, **kwargs):
    res = {}
    for i, a in enumerate(args):
        if isinstance(a, dict):
            res.update(a)
        else:
            res['arg%s' % (i+1)] = a
    res.update(kwargs)
    return res


arg1 = { 'x': 'X', 'y': 'Y' }  
arg2 = 2
arg3 = { 'p': arg1, 'pi': 3.14 }

myDict = func(arg1, arg2, arg3, arg4=4)
print(myDict)

returns:

{'x': 'X', 'y': 'Y', 'arg2': 2, 'p': {'x': 'X', 'y': 'Y'}, 'pi': 3.14, 'arg4': 4}
Maurice Meyer
  • 17,279
  • 4
  • 30
  • 47
  • That's pretty close. One more thing i would like to be there is the element with key `'p'` unpacked. Variables with same names should be in in `myDict` only if their values are the same, if that's not the case then neither of them should be there. – nimi Jun 09 '17 at 08:22
  • This should be done before you pass the args to the function ... I mean, when you create the arg-variables. – Maurice Meyer Jun 09 '17 at 08:29