How to detect what type a variable is?

Tim Chase python.list at tim.thechases.com
Wed Nov 29 12:15:41 EST 2006


>> I want to know what type is a variable.
> 
> You should try to treat it as a list, catch the exceptions
> raise when it is a string (problably ValueError, TypeError ou
> Attribute error, depends on what are you doing), and then
> treat it as a string. This is the BAFP (better ask for
> forgiveness than permission) style


One might prefer to check for string-ness, as strings can 
duck-type somewhat like lists:

my_list = ['my', 'brain', 'hurts']
my_string = 'Are you the brain specialist?'

for test in [my_list, my_string]:
     try:
         for thing in test:
             process_list_item(thing)
     except Exception: #whatever flavor you want
         process_string(thing) # not called because
         #strings are iterable


This gives the potentially-surprising result of iterating over 
my_string and calling process_list_item() with each character in 
the string, rather than raising some exception and calling 
process_string().  Python does the right thing, but it can be 
confusing when the duck-typing syntax is identical for the two, 
despite a desire to treat them differently...perhaps a tree-like 
list of lists and strings such as HTML/XML structure.

-tkc






More information about the Python-list mailing list