0

Given:

  1. a set of class instances (CL) and a reference instance (r)
  2. the class has several getters, such as 'getA', 'getB', ...

Todo: Find those instances from CL that match 'r' by comparing 'getA', 'getB', ... For good code, only one selection function should be written, and you called by giving different getters as the comparison and selection criteria.

My code looks like this:

def selector(r, cl, cmp_function_name):
  return [i for i in CL if getattr(r, cmp_function_name)() == getattr(i, cmp_function_name)()]
# call it like this:
selector(r, cl, 'getA')
selector(r, cl, 'getB')
...

But I am not sure this is neat or pythonic. What do you think about it and How would you code it?

Thanks!

Shawn Chin
  • 84,080
  • 19
  • 162
  • 191
lukmac
  • 4,617
  • 8
  • 33
  • 34

1 Answers1

2

I think your selector is fine; here are two suggestions to make it slightly quicker and more pythonic.

  1. Do not recompute getattr(r, cmp_function_name)() for every item in CL. Compute it once and save it:

    def selector(r, CL, cmp_function_name):
       refval = getattr(r, cmp_function_name)
       return [i for i in CL if getattr(i, cmp_function_name) == refval]
    
  2. Also, in Python, if your getters take no arguments, use properties instead of getters:

    class CLClass(object):
        @property
        def A(self):
    

    instead of

    class CLClass(ojbect):
        def getA(self):
    

    Then you can access the property with obj.A instead of obj.getA().

Community
  • 1
  • 1
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677