0

Just wanted to know if this is a bad convention (which I am assuming is the case):


def foo(*args, **kwargs):
    locals().update(kwargs)
    try:
        print(args, kwargs, a)
    except NameError:
        print('"a" is not defined')

Why do this?

Suppose you have a python dict which serves as a config. This config may be lengthy and as a lazy programmer you do not want to have an enormous def statement naming the kwargs, you also do not necessarily always want to write kwargs["my_var"] or inside the function def write my_var = kwargs["my_var"].

Again I think this is not the best way to handle it. I am just curious if there might be another solution.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
SumNeuron
  • 4,850
  • 5
  • 39
  • 107
  • You can't alter function locals, because changes to the `locals()` dictionary *are not reflected back*. – Martijn Pieters Mar 02 '19 at 14:59
  • So it's not a bad idea, nor is it a good idea, because *it doesn't do anything to anything other than the dictionary `locals()` returned*. – Martijn Pieters Mar 02 '19 at 14:59
  • @MartijnPieters in my console if I run `foo(a=1)` it prints if I run `foo(1,2,3)` it throws the error suggesting that the `locals()` dict is actually updated... – SumNeuron Mar 02 '19 at 15:00
  • Putting configuration in a dictionary is great. You don't need to put all of those key-value pairs into local variables, just use the dictionary directly. – Martijn Pieters Mar 02 '19 at 15:00
  • Local names in functions are determined at compile time, and CPython uses an array to store them. The dictionary `locals()` returns is created by copying the values from the array to a dictionary together with the local variable names stored in the code object to form the keys. You can't add more locals by writing to `locals()`. Sorry. – Martijn Pieters Mar 02 '19 at 15:02
  • @MartijnPieters ok :) thank you for your guidence – SumNeuron Mar 02 '19 at 15:02

0 Answers0