0

I have a function that depending on a keyword argument ('criteria'), will have a variable number of additional keyword arguments. While I can assign these additional keyword arguments to variables for the function, I want to know if there's any way to automatically create variables based on the keyword argument dictionary of keys and values. My working test code is this:

from numpy import nonzero
from numpy.linalg import norm

def subdivide(criteria=None, **kwargs):
    if not criteria:
        raise KeyError
    if criteria == 'curvature':
    k = norm(kwargs['kb'], axis=1)
    k_limit = kwargs['k_limit']
    indices = nonzero((k > k_limit))[0]
    if criteria == 'rotation':
        theta = kwargs['theta']
        theta_limit = kwargs['theta_limit']
        indices = nonzero((theta > theta_limit))[0]
    if criteria == 'rotation & curvature':
        k = norm(kwargs['kb'], axis=1)
        k_limit = kwargs['k_limit']
        theta = kwargs['theta']
        theta_limit = kwargs['theta_limit']
        indices = nonzero((k > k_limit) * (theta > theta_limit))[0]
    return indices

if __name__ == '__main__':
    from numpy.random import rand
    from numpy import array, zeros

    test_kb = array(rand(100, 3))
    theta0 = array(rand(100))
    k0_limit = 1.0
    th_limit = 0.5
    indices = subdivide(criteria='curvature', kb=test_kb, k_limit=k0_limit)
    indices = subdivide(criteria='rotation & curvature', kb=test_kb, 
    theta=theta0, k_limit=k0_limit, theta_limit=th_limit)

I would like to be able to have a general snippet before evaluating the criteria such that I do not have to assign the keyword explicitly to a variable within each if statement. Something like:

for key, value in kwargs:
   ... make key variable, assign value to key
petezurich
  • 9,280
  • 9
  • 43
  • 57
stagermane
  • 1,003
  • 2
  • 12
  • 29
  • 1
    why do you need this? why don't you get values by keys from the ```kwargs``` dictionary? could you provide and example of what you want to do? – py_dude Nov 29 '17 at 11:55
  • perhaps using the `locals()` dict. It is not very explicit though. What if those key words are not set? – Paul Rooney Nov 29 '17 at 11:57
  • And how would you recognize a valid argument (one you expect) from an invalid one (one that should be inserted) in that case? – Eypros Nov 29 '17 at 12:03
  • For each criteria option, if the necessary variable doesn't exist in the input keywords, I would assume it would throw an error when trying to evaluate indices. I am trying to automatically create variables based on the kwarg key, so rather than having to explicitly assign k_limit = kwargs['k_limit'], k_limit would already be available as that variable. – stagermane Nov 29 '17 at 12:06
  • @Eypros, if this is a fundamentally bad idea, that's fine. I'm just curious if there's a way to automate variable creation from the keyword arguments. – stagermane Nov 29 '17 at 12:14
  • `for key, value in kwargs.iteritems(): setattr(self, key, value)` would work if you were inside a class structure. assigns the key to a class variable. – Luke.py Nov 30 '17 at 12:41
  • What if someone writes something like `subdivide(..., nonzero=1, norm=2)` etc. Is that not breaking your code? (`nonzero` and `norm` are globals you are referring in your function) – Abdul Aziz Barkat Feb 17 '23 at 08:41
  • Does this answer your question? [Convert dictionary entries into variables](https://stackoverflow.com/questions/18090672/convert-dictionary-entries-into-variables) – Abdul Aziz Barkat Feb 17 '23 at 08:44

1 Answers1

2

Try this

def my_function(**kwargs):
    for key, value in kwargs.items():
        locals()[key] = value
    print(f"Local variable 'name' is {name}")
    print(f"Local variable 'age' is {age}")

my_function(name="John", age=30)
aldennis
  • 51
  • 3