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