[Tutor] List methods/comps Best Practices

Karl Pflästerer khp at pflaesterer.de
Mon Apr 3 18:20:06 CEST 2006


On  3 Apr 2006, stvsmth at gmail.com wrote:

> I had several list comprehensions that I was mucking with; these lists
> are working on a simple subclass of the built-in list object. They
> looked liked this:
>
>   filelist = getFilesToAdd()
>   filelist2 = getFilesToDel()
>
>   adds = MyList('foo')
>   dels = MyList('bar')
>
>   [adds.add_changes('foo', path) for path in filelist]
>   [dels.add_changes('bar', path) for path in filelist2]
>
>   # return all changes, deletes first
>   return dels.extend(adds)
>
> Since extend returns None, I ran into a lot of not-iterable errors
> when calling this code. So I fixed this with
>
>   dels.extend(adds)
>   return dels
>
> And all is good, although it took way more head scratching than typing
> . (In writing this, I now vaguely remember one of my tutorials warning
> me about something ... maybe this was that? :)
>
> So my question is this: Is this just one of those things that I learn
> the hard way in Pthon & that's it, or am I doing something weird? I
> shoulda figured this out when I was debugging the method in the
> interpreter and my original list comprehensions returned
>
>   [adds.add_changes('foo', path) for path in filelist]
>   >>> [None, None, None]
>
> as each call to add_changes returned no value. Alas, I'm not that
> smart. Is it bad form to not have an "assignment" for the list comps?

In short: IMO yes it's not good practice; the list comprehension is used
to create a list. If you don't need the list write a loop.
So don't write:
[adds.add_changes('foo', path) for path in filelist]
but:
for path in filelist: adds.add_changes('foo', path)

Or show us more explicitly what you want to achieve, sice you don't tell
us what add_changes() does.



   Karl
-- 
Please do *not* send copies of replies to me.
I read the list


More information about the Tutor mailing list