-1

In a function def test(**params), how do I use the keys of **params to create variables named by kwargs.keys() with values kwargs.values() that I can use inside of my function test?

jjjjjj
  • 1,152
  • 1
  • 14
  • 30
  • 4
    Why not just use `params['keyname']`? Why do you need separate local variables? You can't dynamically add new local names to a function body. – Martijn Pieters Jun 30 '17 at 18:40
  • 1
    Even if you did that, say they call `test(foo=3)` and you make a `foo` local variable initialized to `3`. Unless the body of `test` already uses `foo`, you basically can't do anything with this variable, and if it *does* already use `foo`, why didn't you define a regular `foo` argument instead of just `**params`? – user2357112 Jun 30 '17 at 18:45

1 Answers1

-2

EDIT: This approach doesn't work in most circumstances. I tested it in IPython where it does work in the outer context.

You should just use the kwargs __get__ lookup. It is bad practice to do this,

~~but if you insist on creating these variables you can do: locals().update(kwargs). Doing this makes this code valid:~~

def foo(**kwargs):
   locals().update(kwargs)
   return a + 3

print(foo(a=3))

~~will output 6~~

will output NameError: name 'a' is not defined


EDIT: This works

I'm actually quite surprised that updating locals doesn't work in the standard interpreter. I also found that eval doesn't work either. I've been using tricks like this in IPython for years. Looking at Modifying locals in Python it seems like you used to be able to do this in Python 2 using exec, but its no longer valid in Python 3 (which is probably a good thing).

However, I have found a hack that I believe works. Again, please don't do this in practice.

def foo(**kwargs):
    foo.__globals__.update(kwargs)
    return a + 3

print(foo(a=3))
Erotemic
  • 4,806
  • 4
  • 39
  • 80
  • 1
    Yet again, I must point out that [no, this doesn't actually work](http://ideone.com/XT1WzC). – user2357112 Jun 30 '17 at 18:50
  • 1
    From the [docs](https://docs.python.org/3.6/library/functions.html#locals): "Note The contents of this dictionary should not be modified; changes may not affect the values of local and free variables used by the interpreter." – juanpa.arrivillaga Jun 30 '17 at 18:53
  • Yes, but this now pollutes the *global scope*. Also, modifying `locals` doesn't work in IPython either, so I'm not sure what behavior you've been seeing. – juanpa.arrivillaga Jul 01 '17 at 20:23
  • @juanp.arrivillaga modifying locals will work in IPython if you are in the namespace of the interactive terminal. It doesn't work in function definitions though. – Erotemic Jul 02 '17 at 17:33