Search code examples
pythonjsontypechecking

What is the Pythonic Way of Differentiating Between a String and a List?


For my program I have a lot of places where an object can be either a string or a list containing strings and other similar lists. These are generally read from a JSON file. They both need to be treated differently. Right now, I am just using isinstance, but that does not feel like the most pythonic way of doing it, so does anyone have a better way of doing it?


Solution

  • No need to import modules, isinstance(), str and unicode (versions before 3 -- there's no unicode in 3!) will do the job for you.

    Python 2.x:

    Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29) 
    [GCC 4.2.1 (Apple Inc. build 5646)] on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    >>> isinstance(u'', (str, unicode))
    True
    >>> isinstance('', (str, unicode))
    True
    >>> isinstance([], (str, unicode))
    False
    
    >>> for value in ('snowman', u'☃ ', ['snowman', u'☃ ']):
    ...     print type(value)
    ... 
    <type 'str'>
    <type 'unicode'>
    <type 'list'>
    

    Python 3.x:

    Python 3.2 (r32:88445, May 29 2011, 08:00:24) 
    [GCC 4.2.1 (Apple Inc. build 5664)] on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    >>> isinstance('☃ ', str)
    True
    >>> isinstance([], str)
    False
    
    >>> for value in ('snowman', '☃ ', ['snowman', '☃ ']):
    ...     print(type(value))
    ... 
    <class 'str'>
    <class 'str'>
    <class 'list'>
    

    From PEP008:

    Object type comparisons should always use isinstance() instead of comparing types directly.