20

I would like to my function func(*args, **kwargs) return one dictionary which contains all arguments I gave to it. For example:

func(arg1, arg2, arg3=value3, arg4=value4)

should return one dictionary like this:

{'arg1': value1, 'arg2': value2, 'arg3': value3, 'arg4': value4 }
nimi
  • 391
  • 1
  • 2
  • 10
  • looks like the same problem here https://stackoverflow.com/questions/582056/getting-list-of-parameter-names-inside-python-function – Artem Kryvonis Jun 07 '17 at 12:31
  • 3
    Sounds like an XY problem; since you could simply call `dict(arg1=arg1, arg2=arg2, arg3=value3, arg4=value4)`. What are you actually trying to accomplish? – chepner Jun 07 '17 at 12:36
  • @chepner `arg1 = { 'x': 'X', y': 'Y'}` `arg2 = 2`, function `func(arg1, arg2, arg3= 3)` should return `{'x': 'X', y': 'Y, 'arg2': 2, 'arg3':3} – nimi Jun 07 '17 at 12:54
  • 1
    OK, that's a significantly different outcome than what you are asking about in your question. – chepner Jun 07 '17 at 13:12

3 Answers3

27

You can use locals() or vars():

def func(arg1, arg2, arg3=3, arg4=4):
    print(locals())

func(1, 2)

# {'arg3': 3, 'arg4': 4, 'arg1': 1, 'arg2': 2}

However if you only use *args you will not be able to differentiate them using locals():

def func(*args, **kwargs):
    print(locals())

func(1, 2, a=3, b=4)

# {'args': (1, 2), 'kwargs': {'a': 3, 'b': 4}}
DeepSpace
  • 78,697
  • 11
  • 109
  • 154
  • 1
    Your first output seems strange, arg3&arg4 have values 1&2 instead of 3&4. It should be : `{'arg1': 1, 'arg2': 2, 'arg3': 3, 'arg4': 4}` – Nuageux Jun 07 '17 at 12:39
  • @Nuageux Indeed, was just a copy-paste error. I fixed it. – DeepSpace Jun 07 '17 at 12:41
  • What if i give dictionary as argument? I will get this `{ 'args': ({'argX': 'x', 'argY': 'y}, 'arg1': 1) , kwargs': {}} ` instead o this `{'arg1': 1, 'argX': 'x', 'argY': 'y'} ` – nimi Jun 07 '17 at 12:50
  • @NikolaMijušković see the "However" part of my answer – DeepSpace Jun 07 '17 at 12:51
4

You are looking for locals()

def foo(arg1, arg2, arg3='foo', arg4=1):
    return locals()

{'arg1': 1, 'arg2': 2, 'arg3': 'foo', 'arg4': 1}

Output:

{'arg1': 1, 'arg2': 2, 'arg3': 'foo', 'arg4': 1}
Arount
  • 9,853
  • 1
  • 30
  • 43
  • 4
    `locals` is too broad if there are local variables other than the arguments. – chepner Jun 07 '17 at 12:35
  • @chepner i presume if you call the as soon as the function is called then it will only list arguments? You could store this as a new variable i think? – Nick W. Jun 29 '21 at 02:07
2

If you can't use locals like the other answers suggest:

def func(*args, **kwargs):
    all_args = {("arg" + str(idx + 1)): arg for idx,arg in enumerate(args)}
    all_args.update(kwargs)

This will create a dictionary with all arguments in it, with names.

acdr
  • 4,538
  • 2
  • 19
  • 45