Home > Mobile >  How to edit own kwargs from inside a function?
How to edit own kwargs from inside a function?

Time:01-05

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?

CodePudding user response:

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)

CodePudding user response:

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.

  •  Tags:  
  • Related