Thread: Type Checking?

    #1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2003
    Posts
    81
    Rep Power
    12

    Type Checking?


    Ok here is what I am trying to do. I have a list and it has some strings in it, but it also has some lists in it. Once I grab an element from the list, how do I check if it is a list or a string, etc. Thanks!
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2003
    Posts
    133
    Rep Power
    12
    There are several ways:
    Code:
    >>> type([1, 2]) is list
    True
    >>> type([1, 2]) is str
    False
    >>> isinstance([1, 2], list)
    True
    >>> isinstance("text", basestring)
    True
    >>> isinstance("text", str)
    True
    >>> isinstance(u"text", str)
    False
    >>> isinstance(u"text", unicode)
    True
    A string can be of type str or of type unicode. Check if it's an instance of basestring instead.
    Last edited by percivall; April 1st, 2004 at 10:57 AM.
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Feb 2004
    Location
    London, England
    Posts
    1,585
    Rep Power
    1373
    use the type(x) builtin function.

    From the manual:

    type( object)

    Return the type of an object. The return value is a type object. The standard module types defines names for all built-in types that don't already have built-in names. For instance:

    >>> import types
    >>> x = 'abc'
    >>> if type(x) is str: print "It's a string"
    ...
    It's a string
    >>> def f(): pass
    ...
    >>> if type(f) is types.FunctionType: print "It's a function"
    ...
    It's a function

    The isinstance() built-in function is recommended for testing the type of an object.
    To check for strings it is safer to use isinstance(x, types.StringTypes), since that will succeed for both regular strings and unicode strings.


    Dave - The Developers' Coach
    Last edited by DevCoach; April 1st, 2004 at 11:01 AM.
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2001
    Location
    Houston, TX
    Posts
    383
    Rep Power
    13
    Originally Posted by jimo9
    Ok here is what I am trying to do. I have a list and it has some strings in it, but it also has some lists in it. Once I grab an element from the list, how do I check if it is a list or a string, etc. Thanks!
    The pythonic way is to not check the type, but simply to do whatever actions you would do to the string and if any object happens to fit those criteria, allow it to do so. That way you can have string-like classes/objects that will also be usable in that function without having to constantly add special cases in your type checking.
    Debian - because life's too short for worrying.
    Best. (Python.) IRC bot. ever.
  8. #5
  9. No Profile Picture
    Contributing User
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Feb 2004
    Location
    London, England
    Posts
    1,585
    Rep Power
    1373
    Originally Posted by Strike
    The pythonic way is to not check the type, but simply to do whatever actions you would do to the string and if any object happens to fit those criteria, allow it to do so. That way you can have string-like classes/objects that will also be usable in that function without having to constantly add special cases in your type checking.

    Good point. If you want to check the type of an object so that you can raise an exception if it not what you expect, then you are better off just using it and seeing what happens.

    However there are times when you do want to check the type so that you can take different actions depending on what the object is. A common case is to distinguish between strings and other sequence objects.
    Here is an example - a generator that converts a nested sequence into a flattened, non-nested sequence:

    Code:
    import types
    
    def flatten(seq):
    	if isinstance(seq, types.StringTypes):
    		yield seq
    	elif hasattr(seq, '__iter__'):
    		for item in seq:
    			for element in flatten(item):
    				yield element
    	else:
    		yield seq
    		
    >>> x = [['foo, bar', ('one', 'two', 'three')], ('four', 'five'), 4, (6,7)]
    >>> list(flatten(x))
    ['foo, bar', 'one', 'two', 'three', 'four', 'five', 4, 6, 7]
    >>>
    If it did not check for a string before checking for a sequence then it would go into an infinite recursive loop, since the characters in a string are also strings.

    Dave - The Developers' Coach

IMN logo majestic logo spyfu logo threadwatch logo seochat tools logo