Re: How to detect what type a variable is?



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



.



Relevant Pages

  • TOC of Python Cookbook now online (was Re: author index for Python Cookbook 2?)
    ... Processing a String One Character at a Time ... Finding a File on the Python Search Path ... Constructing Lists with List Comprehensions ... Looping over Items and Their Indices in a Sequence ...
    (comp.lang.python)
  • ANN: MeObjects Library for Delphi
    ... object type small and powerful. ... the Object instance can use the ClassType method return the ... Especially for lists of pointers to dynamically allocated memory. ... {Summary Adds Ansi String and correspondent object to a list. ...
    (borland.public.delphi.thirdpartytools.general)
  • Filling a grid with Sharepoint data
    ... /// Retrieves a Lists web service proxy with default settings. ... string strComputerName = System.Net.Dns.GetHostName.ToLower; ... XmlDocument xmlDoc, ... XmlElement elementMethod, ...
    (microsoft.public.dotnet.framework.windowsforms)
  • Re: Code for List Boxes
    ... I also had to add a closing parentheses to strWhere = ... Dim strWhere As String ... Dim varSelected As Variant ... when you've selected values from the two lists? ...
    (microsoft.public.access.modulesdaovba)
  • Re: Can Dir handle different file types?
    ... Dim list As String ... Public Function ListFiles(Paths As String, Patterns As String, Optional ListCount As Long = 0) As String ... Dim pathIndex As Long, patternIndex As Long, listPosition As Long ... ' Accept lists that start with up to 2 delimiters ...
    (microsoft.public.vb.general.discussion)