Ejonas Ejonas - 2 months ago 9
Python Question

Using named arguments as variables

I am using django but I think this question primarily belongs to Python itself.

I have something like:

def get(self, request, arg, *args, **kwargs):

if kwargs['m0'] == 'death':
if kwargs['m1'] == 'year':
result = Artists.objects.filter(death_year=arg)
elif kwargs['m1'] == 'month':
result = Artists.objects.filter(death_month=arg)
elif kwargs['m1'] == 'day':
result = Artists.objects.filter(death_day=arg)
elif kwargs['m0'] == 'birth':
if kwargs['m1'] == 'year':
result = Artists.objects.filter(birth_year=arg)
elif kwargs['m1'] == 'month':
result = Artists.objects.filter(birth_month=arg)
elif kwargs['m1'] == 'day':
result = Artists.objects.filter(birthh_day=arg)


Where
death_year
is a named argument that is a field in my model
Artists
representing a column in my database. The variables 'm0' and
m1
are passed from the
urlconf
to my get function (it is actually a
get
method in my view class).
Can I control the name value of the variable
death_year
without using an if else if chain (i.e. make it
death_month
or
birth_year
)? Since I have many choices, I will have to use a ridiculously very long conditional chain that leads to this same line but with just a different named argument.

I strongly doubt that you should understand this whole problem to answer the question. The original question is simple: Can I use a named argument and its corresponding value as variables in Python?

Answer

From what I can make out you can construct the key and then pass in an arg to construct the dict, then include that in the filter

key = '%s_%s' % (kwargs['m0'], kwargs['m1'])
result = Artists.objects.filter(**{key: arg})
Comments