detecting variable types

Bengt Richter bokr at
Wed Sep 22 23:00:49 CEST 2004

On Wed, 22 Sep 2004 15:45:55 -0400, "Jay" <wjjeonk at> wrote:

>Thanks, Peter.
Please don't top-post, ok? Notice what it does to the order
of your comments and mine vs Peters'. Insert your comments below
quoted material it refers to, then order can be preserved through
several generations. Stacking wholes monolithically preserves order
too, but it gets harder to indicate where in the following monoliths
your top-posted comments apply.

>Here's what I'm trying to do:
>I have a function like this:
>def func(**params):
>    # if params[key1] is a single string
>        # do something with params[key1]
>    # if params[key1] is a list of strings
>        for val in params[key1]:
>            # do something
>Could you suggest a better way to do this without detecting the type?
That particular distinction is extra nasty because strings are also iterable.

One trouble with type(arg)==list or type(arg)==str is that if your calling
program wants to pass a list or str subtype later, you will have to change
your func code to detect the new type, even though it behaves the same.

So you usually better off with an isinstance(arg, str) than a type(arg)==str test.

 >>> class S(str): pass
 >>> s=S('hello')
 >>> s
 >>> type('hello')
 <type 'str'>
 >>> type(s)
 <class '__main__.S'>
 >>> isinstance('hello', str)
 >>> isinstance(s, str)

 >>> type('hello')==str
 >>> type(s)==str

Sometimes you do actually need that distinction though.

>"Peter Hansen" <peter at> wrote in message
>news:Y-WdnWCkPIytTszcRVn-vQ at
>> Jay wrote:
>> > I'm sure this is a really dumb question, but how do you detect a
>> > type in Python?
>> >
>> > For example, I want to know if the variable "a" is a list of strings or
>> > single string. How do I do this?
>> Use the builtin function "type()", but note the following:
>> 1. Variables don't actually have types in Python (and they're usually
>> called "names" in Python, for various reasons), but the data they are
>> currently bound to does have a type and that's what type() returns.
>> Often the distinction won't matter to you...
>> 2. Most of the time people trying to do what you are probably trying
>> to do are going about things the wrong way, often from experience
>> with other languages.  Lots of Python folks would be happy to introduce
>> you to "better" ways to do things, if you'll explain the use case
>> and tell us what you're actually trying to accomplish.  (Of course,
>> using "type()" will work, but it's rarely considered the best
>> approach in the Python community.)
>> -Peter

Bengt Richter

More information about the Python-list mailing list