0

I have a long and complicated method, I'll give the important parts:

def get_itter(self, sort_by=0): #sort_by is set to 0 for debugging purposes

    ...

    r = self.parser(self.in_file) # parse a csv file

    ...

    if type(sort_by) == int:
        r = [i for i in r]
        sort = sorted(r, key=sort_by)
    ...

Now my problem is that when I run this code it gives me an error: TypeError: 'int' object is not callable. Why is it giving me this error?

P.S. I am relatively new to Python and am trying to add some functionality to code that I did not write.

6
  • What kind of sorting were you expecting to happen? Commented Jan 30, 2014 at 14:44
  • @MartijnPieters I have a csv file full of dates, and I need to sort the csv file by date. so that I can run it trough a custom parser and import the data to the system Commented Jan 30, 2014 at 14:47
  • And what is sort_by supposed to represent? The column number? Commented Jan 30, 2014 at 14:48
  • Indeed it does represent the column number. :) Commented Jan 30, 2014 at 14:49
  • Then jonrsharpe's answer has got you covered; use itemgetter() as the sort key. And use isinstance(sort_by, int) instead of testing for a fixed type. Commented Jan 30, 2014 at 14:54

2 Answers 2

5

You set:

sort_by=0

check it's an int

if type(sort_by) == int: # note: isinstance(sort_by, int) is preferred here

then use it:

sorted(r, key=sort_by)

When you pass a key to sorted, it tries to apply that key to all items in the sequence it's sorting, trying to call it with each item, something like:

sortvalues = [key(i) for i in seq]

If key is an integer, you can't call it:

0(1)

gives the TypeError you are seeing.

It's not clear exactly what you're trying to do, but if you want to sort by the sort_byth item in a sequence, you can use operator.itemgetter:

from operator import itemgetter
sorted(r, key=itemgetter(sort_by))
Sign up to request clarification or add additional context in comments.

Comments

1

You set sort_by to 0 and then pass that as the key function to sorted. Python will call key as a function to define the sorting key, which isn't possible for 0.

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.