[Tutor] Wrapping with list
Alan Gauld
alan.gauld at btinternet.com
Fri Sep 13 18:57:20 CEST 2013
On 13/09/13 11:24, Dotan Cohen wrote:
> A function that I wrote works on a list or on a string. If the
> function is passed a string, then it wraps the string in a list at the
> top of the function. Is it bad form to wrap the string in place?
It depends what your function does. In most cases the string
and list sequence methods work (strings are immutable lists
are mutable so they can't be used identically). So maybe you
want to treat the string as a sequence of chars. OTOH if
you want to treat the string as a single element list
then wrapping it makes sense.
It all depends what your function does.
> if not isinstance(someVar, list):
> someVar = [someVar]
Is that really what you want? What if a set, tuple or dict
is passed in? Do you want to create a list containing the
tuple or do you want to convert the tuple to a list?
It depends what the function does.
But if you only want to special case strings you would
be better using
if isinstance(someVar, str): someVar = [someVar]
> To avoid that, I am creating a list then appending the original value:
>
> if not isinstance(someVar, list):
> temp = someVar
> someVar = []
> someVar.append(temp)
Your first attempt is much simpler and produces an identical result.
> Is my prudence unwarrented?
Yes, it's just creating lots more work.
But I'd consider if you can write the function such that it doesn't rely
on types at all, can you use a subset of functions/methods that work on
all/most sequence types? Then catch exceptions using a try/except construct?
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list