How can I test if an argument is a sequence or a scalar?

Russell E. Owen rowen at cesmail.net
Wed Jan 11 14:07:14 EST 2006


In article <1136935102.587013.67160 at o13g2000cwo.googlegroups.com>,
 sandravandale at yahoo.com wrote:

>I want to be able to pass a sequence (tuple, or list) of objects to a
>function, or only one.
>
>It's easy enough to do:
>
>isinstance(var, (tuple, list))
>
>But I would also like to accept generators. How can I do this?
>
>Anything else is assumed to be a single value (my fault if I pass a
>dict or something else to the function) and I make it into a tuple with
>a single value (var, ) in order to simplify the algorithm (wasn't there
>a special name for a one item tuple? Its been a while since I've
>programmed in Python.)
>
>Is there an easy way to do that?

Here is the code I use for that purpose, but it does not handle 
generators or iterators. You could easily combine this with code 
suggested in other replies to accomplish that. (I intentionally excluded 
iterators because I didn't need them and they can be unbounded. Still, 
now that they are so widely used it may be worth reconsidering.)

def isSequence(item):
    """Return True if the input is a non-string sequential collection,
    False otherwise. Note: dicts and sets are not sequential.
    """
    try:
        item[0:0]
    except (AttributeError, TypeError):
        return False
    return not isString(item)

def isString(item):
    """Return True if the input is a string-like sequence.
    Strings include str, unicode and UserString objects.
    
    From Python Cookbook, 2nd ed.
    """
    return isinstance(item, (basestring, UserString.UserString))

def asSequence(item):
    """Converts one or more items to a sequence,
    If item is already a non-string-like sequence, returns it unchanged,
    else returns [item].
    """
    if isSequence(item):
        return item
    else:
        return [item]

I then use asSequence on each argument that can either be one item or a 
sequence of items (so I can always work on a sequence).

-- Russell

P.S. this code is from RO.SeqUtil 
<http://www.astro.washington.edu/rowen/ROPython.html>



More information about the Python-list mailing list