Re: Newbie help - test for data type



Jonathan Bowlas wrote:
Hi Listers,

I have a requirement to test for a data type could someone tell me if this
is possible in python?

Basically I have a ZPT in Zope that users can select checkboxes in a form
which pass arguments for a python function, however if there is only one
checkbox selected it is passed as a string whereas more than one checkbox is
passed as a list. Therefore if my function is required to perform an action
based on each argument passed in the list the function works correctly but
if it is passed as a string nothing happens.

You need the isinstance() function. For example you can use
isinstance(selecteddeptcodes, list) to test if your variable is a list. If you want to test the other way round use isinstance(selecteddeptcodes, str) if your variable is a string, isinstance(selecteddeptcodes, unicode) if it's a unicode string or isinstance(selecteddeptcodes, basestring) to test if it's a string or unicode string. Read more about this function and the types to test for in http://docs.python.org/lib/built-in-funcs.html.

If you already have the code for a list argument I'd check if it's not a list and then turn it into a list:


if not isintance(selecteddeptcodes, list):
selecteddeptcodes = [selecteddeptcodes]



Bye,
Dennis
.



Relevant Pages

  • Linguistically correct Python text rendering
    ... Unicode strings in Python? ... let's say I create this Unicode string in Arabic: ... is not correct rendering behavior for Arabic. ...
    (comp.lang.python)
  • Re: byte count unicode string
    ... in a "UTF-8 encoded Python string object", ... A Python Unicode string is an abstract sequence of ... UTF-8 is a character encoding; ...
    (comp.lang.python)
  • Re: byte count unicode string
    ... in a "UTF-8 encoded Python string object", ... A Python Unicode string is an abstract sequence of ... UTF-8 is a character encoding; ...
    (comp.lang.python)
  • Re: Problem with sets and Unicode strings
    ... So this is a bug in Python? ... statement directly compares a unicode string with a byte string. ... The string in all of the containers is a regular byte string, not a Unicode string. ... The string literal that you use for FIELDS is a regular string literal, not a Unicode string literal, so the object it creates is an 8-bit byte string. ...
    (comp.lang.python)
  • Re: Nimrod programming language
    ... but your string functions should be aware of that ... and treat it as a unicode string. ... I suppose that is to make it possible to use the 'bytes' data type for ...
    (comp.lang.python)