sending string or list to a function

Gabriel Genellina gagsl-py at yahoo.com.ar
Mon Dec 4 19:58:47 EST 2006


At Monday 4/12/2006 21:20, manstey wrote:

>Is there a neat way to write a function that can receive either a
>string or a list of strings, and then if it receives a string it
>manipulates that, otherwise it manipulates each string in the list?
>
>That is, rather than having to send a list of one member
>MyFunction(['var1']), I can send
>
>MyFunction('var1')  or MyFunction(['var1','var2',var3'])

That depends a bit on what you do with the argument. Sometimes it's 
more clear to have two different methods, one for lists and another 
for single items, specially when processing a list is *not* the same 
as processing each item sequentially.
Another reason to have separate methods would be if you expect much 
more calls to the single-item version than the list version.

If you want a combined version which accepts both strings and lists, 
notice that unfortunately (or not!) strings and lists share a lot of 
functionality. So you have to check for strings in your code, else 
the first call would process 'v','a','r','1'.
That is, you usually write something like this:

def MyFunction(arg):
     if isinstance(arg, basestring): arg = [arg] # or perhaps arg,
     ... process ...

So, if you *will* construct a list anyway, using MyFunction(['var1']) 
in the first place would be better.


-- 
Gabriel Genellina
Softlab SRL 

__________________________________________________
Correo Yahoo!
Espacio para todos tus mensajes, antivirus y antispam ¡gratis! 
¡Abrí tu cuenta ya! - http://correo.yahoo.com.ar



More information about the Python-list mailing list