How to tell the difference between string and list

Gerhard Häring gh at ghaering.de
Fri Dec 5 15:58:37 CET 2003


Jan Kokoska wrote:
> Hello,
> 
> I need to recognize 'var' and ['var'], usually I would use:
> 
> if a.__class__() == '':
> 	#string
> elif a.__class__() == []:
> 	#list
> 
> But unfortunately in Zope PythonScripts, where I need to use this, one
> is not supposed to use underscore-prefixed methods as I just found out. 
> 
> I figure this is a question general enough to post here (and not on the
> Zope list), any clues?

Lots of possibilities:

Python 2.2+:

Politically correct:

if isinstance(a, str):
elif isinstance(a, list):

Even more politically correct (Python 2.3+):

if isinstance(a, basestring):
elif isinstance(a, list):

No-bullshit version (Python 2.2+):

if type(a) is str:
elif type(a) is list:

Python 2.1 and even more ancient ones:

if type(a) is type(""):
elif type(a) is type([]):

or

from types import StringType, ListType
if type(a) is StringType:
elif type(a) is ListType

But if you need *any* of these, chances are you should redesign your API so you 
don't need to switch on the type of the parameter. IMO it's generally better to 
have a different method for each type.

-- Gerhard






More information about the Python-list mailing list