Alex Rivera | Logout

What is the pythonic way of checking if an object is a list?

Asked 2009-09-23T04:54:10.003
10

I have a function that may take in a number or a list of numbers. Whats the most pythonic way of checking which it is? So far I've come up with try/except block checking if i can slice the zero item ie. obj[0:0]

Edit:

I seem to have started a war of words down below by not giving enough info. For completeness let me provide more details so that I may pick and get the best answer for my situation:

I'm running Django on Python 2.6 and I'm writing a function that may take in a Django model instance or a queryset object and perform operations on it one of which involves using the filter 'in' that requires a list (the queryset input), or alternately if it is not a list then I would use the 'get' filter (the django get filter).

Edit
Report

1 Answer

0

I think the way OP is doing, checking if it supports what he wants, is ok.

Simpler way in this scenario would be to not check for list which can be of many types depending on definition, you may check if input is number, do something on it else try to use it as list if that throws exception bail out.

e.g you may not want iterate over list but just wanted to append something to it if it is list else add to it

def add2(o):
    try:
        o.append(2)
    except AttributeError:
        o += 2

l=[]
n=1
s=""
add2(l)
add2(n)
add2(s) # will throw exception, let the user take care of that ;)

So bottom line is answer may vary depending on what you want to do with object

answered 2009-09-23T06:16:57.677

Your Answer