detecting variable types

John Roth newsgroups at jhrothjr.com
Wed Sep 22 16:18:50 EDT 2004


"Jay" <wjjeonk at hotmail.com> wrote in message 
news:ciskpq$7f2$1 at news-int.gatech.edu...
> Thanks, Peter.
>
> 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?

I'd strongly suggest making the value of "key1" a list in
all cases, including the case where there is no value:
that is, an empty list.

It makes your processing logic a lot simpler, and even if
you can't make the caller do it that way, the function/method
to preprocess is fairly simple (and also takes care of the
"key not found" case.)

John Roth
>
>
> Jay.
>
>
> "Peter Hansen" <peter at engcorp.com> wrote in message
> news:Y-WdnWCkPIytTszcRVn-vQ at powergate.ca...
>> Jay wrote:
>> > I'm sure this is a really dumb question, but how do you detect a
> variable
>> > type in Python?
>> >
>> > For example, I want to know if the variable "a" is a list of strings or
> a
>> > 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
>
> 




More information about the Python-list mailing list