[silva-dev] Re: Find out data type

Philipp von Weitershausen philipp at weitershausen.de
Fri May 14 08:28:43 CEST 2004


Andy Altepeter wrote:
> Hi Sam,
> 
> I've struggled with this in my rectricted python code.  Normally you can
> use isinstance or type(object).  The standard types module (see
> python.org/docs) contains the stanard types like list,string, tuple,
> etc.
> 
> Restricted code doesn't have access to the types module.  One can do so,
> but I think it's considered a hack?
> 
> Anyways, the way I determine whether a var is an object or a list of
> objects is like this:
> 
> if hasattr(var,'sort'): #assume var is a list
> 
> When you know var is either a list or a string, then there isn't a
> problem with the above, as strings don't have a 'sort' method. You could
> also test for any other method lists have but strings don't.
> 
> Everyone else can feel free to correct me on this programming practice
> ;-)

Yes, it's bad practice :) The type() and insistance() functions are not 
available in Python scripts for good reasons. However, there is the 
special same_type() function:

   a = 'foo'
   b = ['foo', 'bar']
   same_type(a, '') --> True
   same_type(b, []) --> True

Note that in regular Python modules you should use isinstance(a, str) 
(if using Python >=2.2) or type(a) is StringType.

Philipp




More information about the silva-dev mailing list