IsList?

Gerhard Häring gerhard at bigfoot.de
Mon Apr 8 01:36:44 EDT 2002


John wrote in comp.lang.python:
> Hi, How can one know wheter var 'a' is list or not? Is there any
> IsList-like function?

Python 2.2:
    type(a) is list

    but I think it would be better to use

    isinstance(a, list)

    to also test for subclasses of list

Python < 2.2:
    type(a) is type([])

        or

    from types import ListType
    type(a) is ListType

That being said, you normally shouldn't test for the type directly.
It's much better to think which "interface" you want to match, and
then test for this interface. Interfaces are implicit in Python, they
are fulfilled if the methods that make up the interface are present in
a class. So the first step is to decide what your lists have in
common, i. e. which features of them you use. Then test for the list
features you use in your application.

For example, a list is a sequence, just like a tuple is, only that
this sequence is mutable, so you could test for this with a check
like:

#!/usr/bin/env python2.2
# Requires Python >= 2.2
def is_sort_of_a_list(l):
    for method in ['__getitem__', '__setitem__']:
        if method not in dir(l):
            return 0
    return 1

print is_sort_of_a_list([5])    # list
print is_sort_of_a_list((5,))   # tuple
print is_sort_of_a_list("asdf") # string

Of course you need to change the attributes to be tested for the
application you have in mind.

Gerhard
-- 
mail:   gerhard <at> bigfoot <dot> de       registered Linux user #64239
web:    http://www.cs.fhm.edu/~ifw00065/    OpenPGP public key id AD24C930
public key fingerprint: 3FCC 8700 3012 0A9E B0C9  3667 814B 9CAA AD24 C930
reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b')))



More information about the Python-list mailing list