2

So I have a working sorting algorithm in Python. (Its exact contents are irrelevant to this question.) It uses a list called 'people' containing class instances, and the function is hard-coded to sort that list by a specific attribute, 'wealth'.

def my_sort(seq):
    # sorts by seq[n].wealth
    ...
my_sort(people)

Now, I'd like to generalize the function so I could sort by any attribute.

def my_sort2(seq, key):
    # sorts by seq[n].key
    ...
my_sort2(people, wealth)

But this, of course, throws an error, because it doesn't know to consider 'wealth' as a class attribute. So, how is this possible to do?

2
  • Out of curiosity, what's wrong with the default sorting algorithm in Python? Commented Oct 19, 2011 at 15:24
  • I have a habit of doing things the hard way when I notice my skills at some area aren't sufficient. Commented Oct 19, 2011 at 16:07

2 Answers 2

10

You could pass the name of the attribute:

def my_sort2(seq, keyname):
    sort by getattr(seq[n], keyname)

my_sort2(people, 'wealth')

or a getter functor:

def my_sort2(seq, keyfunc):
    sort by keyfunc(seq[n])

my_sort2(people, operator.attrgetter('wealth'))

I prefer the latter approach as it is more generic. For example, it easily allows for computed keys.

Sign up to request clarification or add additional context in comments.

Comments

1

The generic attribute getter function getattr should work:

gettattr(obj, name)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.