How to detect what type a variable is?
Eduardo "EdCrypt" O. Padoan
eopadoan at altavix.com
Wed Nov 29 18:52:01 CET 2006
> 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]:
> for thing in test:
> except Exception: #whatever flavor you want
The exception should be the one that process_list_item raises when it
receives a string instead of a list. if you want to treat strings and
list in different ways, maybe it means that you are doing different
operations on then, like appendind things to the list or whatever. If
not, than you maybe want to test the types.
> process_string(thing) # not called because
> #strings are iterable
What if you invert your code?
for test in [my_string, my_list]:
#suppose process_string_item does some string operation on a
list and gets this
# exception - because if not, I see no meanning in distinguishing then
for thing in test:
But maybe you have a reason to do things to a string that could be
done to a list without raising an exception, but you dont want to do
this to *that* list. My sugestion was to think if there is another
way, and maybe you are right.
Jabber: edcrypt at jabber dot org
GTalk: eduardo dot padoan at gmail dot com
MSN: eopadoan at altavix dot com
More information about the Python-list