detecting variable types
grante at visi.com
Wed Sep 22 22:58:16 CEST 2004
On 2004-09-22, Andrew Koenig <ark at acm.org> wrote:
> "Jay" <wjjeonk at hotmail.com> wrote in message
> news:ciskpq$7f2$1 at news-int.gatech.edu...
>> 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 don't see anything particularly wrong with detecting the type this way:
> if isinstance(params[key1], list):
> for val in params[key1]:
> # do something
> # do something with params[key1]
> Of course that won't work for other kinds of sequences, but if that's what
> you want, then that's what you want.
When I write functions that accept either a list or a single
object, I usually "normalize" the paramter into a list and then
the rest of the function just operates on lists:
if not isinstance(myParameter,list):
myParameter = [myParameter]
for p in myParameter:
Grant Edwards grante Yow! Is this where people
at are HOT and NICE and they
visi.com give you TOAST for FREE??
More information about the Python-list