0

This code:

#!/usr/bin/env python

def f(a):
    print(f"{locals()}")

if __name__ == '__main__':
    f(1)

Output: {'a': 1}

Want to do something like this:

#!/usr/bin/env python

def f(a):
    kwargs["b"] = 2
    print(f"{locals()}")

if __name__ == '__main__':
    f(1)

to get the output {'a': 1, 'b': 2}

What's the right syntax for that?

Velkan
  • 7,067
  • 6
  • 43
  • 87
  • 4
    if you do just `b = 2`, then you will get that output – Matiiss Jan 04 '22 at 15:01
  • 2
    Perhaps you can use the function signature `f(**kwargs)` and then you can access and modify kwargs. – jkr Jan 04 '22 at 15:02
  • 1
    Related to keyword arguments: https://stackoverflow.com/questions/36901/what-does-double-star-asterisk-and-star-asterisk-do-for-parameters – Tzane Jan 04 '22 at 15:03
  • Why are you trying to do this? For example, are you trying to add keyword arguments to pass on to another function? – Solomon Ucko Jan 04 '22 at 15:04
  • @SolomonUcko some code gets a variable from the context, I'm trying to detangle what part of it gets that variable. I thought it does this by calling `locals()`, but if just `b = 2` solves that then it's some other part. – Velkan Jan 04 '22 at 15:08

2 Answers2

0

You have to create your kwargs dict before trying to index it:

def f(a):
    kwargs = locals()
    kwargs["b"] = 2
    print(kwargs)

if __name__ == '__main__':
    f(1)
Tzane
  • 2,752
  • 1
  • 10
  • 21
0

Ok, it's just b = 2.

My actual problem was on the outside with one of the decorators that wanted the function to have one specific argument. Can't do much about that.

Velkan
  • 7,067
  • 6
  • 43
  • 87