How to detect what type a variable is?

Dustan DustanGroups at gmail.com
Wed Nov 29 19:50:39 EST 2006


Eduardo "EdCrypt" O. Padoan wrote:
> >
> > 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
>
> 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]:
>     try:
>         process_string_item(thing)
>         #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

In case you had trouble reading the comments because it was too wide:
"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"

Has it occurred to you that perhaps the OP wants to do very different
operations depending on whether or not the item is of type str or list?
And since a list can in many cases act very similarly to a string, the
best way to distinguish would be a type check, especially since the OP
knows what tools are being used to receive the output.

>     except ValueError:
>         for thing in test:
>             process_list_item(thing)
>
> 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.
>
>
> --
> EduardoOPadoan (eopadoan->altavix::com)
> Bookmarks: http://del.icio.us/edcrypt
> Blog: http://edcrypt.blogspot.com
> Jabber: edcrypt at jabber dot org
> ICQ: 161480283
> GTalk: eduardo dot padoan at gmail dot com
> MSN: eopadoan at altavix dot com




More information about the Python-list mailing list