1

Is there any way to assign operators to variables? I have function

def get_age(age=0, year_level_from=0, year_level_to=0):
    overall = []
    for level in range(year_level_from, year_level_to):
        if age <= 11:
           operator = <=
        else:
           operator = >=
        male_count = len([
            info for info in queryset
            if info.age **operator** age
            if info.gender == 'male'
            if info.year_level == level
        ])
        overall.append(male_count)

I want to declare like get_age(age=11, year_level_from=1, year_level_to=7) if this is possible so this function have the ability to choose those age with that condition I want to get. thanks in advance

denmg
  • 360
  • 3
  • 12

1 Answers1

3

Yes, you can use the operator library: (You'll obviously have to use a different name than operator for the variable in that case!) Usage would be like the below (only the significant lines shown to give you the idea):

import operator
...
if age <= 11
    compare_function = operator.le
...
[...
if compare_function(info.age, age):
...]

Or if you don't want to import that for some reason, it's not too hard to define these on your own with lambda functions, eg:

if age <= 11:
    operator = lambda a, b: a <= b

And use as

if operator(info.age, age)

inside your list comprehension.

Robin Zigmond
  • 17,805
  • 2
  • 23
  • 34