Re: How to detect what type a variable is?
- From: Tim Chase <python.list@xxxxxxxxxxxxxxxxx>
- Date: Wed, 29 Nov 2006 11:15:41 -0600
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
.
- References:
- How to detect what type a variable is?
- From: Leandro Ardissone
- Re: How to detect what type a variable is?
- From: eduardo.padoan@xxxxxxxxx
- How to detect what type a variable is?
- Prev by Date: pickle and infinity
- Next by Date: Re: pickle and infinity
- Previous by thread: Re: How to detect what type a variable is?
- Next by thread: Re: How to detect what type a variable is?
- Index(es):
Relevant Pages
|