Re: [Tutor] PolyRange -- iterator
by Stefan Lesicnik other posts by this author
Nov 4 2009 10:33AM messages near this date
Re: [Tutor] PolyRange -- iterator -- PS
|
[Tutor] why is os.path.walk so slow?
On Wed, Nov 4, 2009 at 7:17 PM, Hugo Arts <hugo.yoshi@[...].com> wrote:
> On Wed, Nov 4, 2009 at 5:38 PM, spir <denis.spir@[...].fr> wrote:
> > Hello,
> >
> > as I was crawling in endless complications with unadequate ranges, I decided to create a
"PolyRange" type able to hold arbitrary many "sub-range"; which means finally a big range wi
th wholes in it. This whole stuff again to cope with unicode -- a poly-range would be able t
o hold a range for a char class (eg 'letter') which spans over several ordinal ranges. (Viva
unicode consortium!)
> >
> > So, it works as needed. It is even able to "stretch" over addictional sub-ranges or to "u
nite" with a poly-range brother (sister, too). See code below.
> >
> > Now, I need it to be properly iterable if needed -- the main use beeing indeed the 'in' o
perator -- but who knows. So, I tried to implement __iter__ and next (by the way, why isin't
it called __next__ instead, looks strange for a python builtin?). Seems to work, but the re
sult looks veeery heavy to my eyes. As I had never written an iterator before, would be nice
and criticize the code?
> >
>
> You're right, next() should really be called __next__(), and this is
> actually fixed in python 3 (don't know why it wasn't originally done
> this way).
>
> Now, the code. If you write __iter__ as a generator, you won't have to
> write a next method at all. It simplifies The thing a whole lot:
>
> def __iter__(self):
> Â Â for range in self.ranges:
> Â Â Â Â for item in range:
> Â Â Â Â Â Â yield item
>
> That's it. Alternatively, you could turn the whole thing into a
> one-liner and just return a generator expression from __iter__:
>
> def __iter__(self):
> Â Â return (item for r in self.ranges for item in r)
>
> It's not as clear though, and it doesn't save that much space. I like
> the first one slightly better.
>
> python documentation on generators:
> http://docs.python.org/tutorial/classes.html#generators
I dont know much about generators, but this link was posted earlier
this week and i learnt alot from it (actually some basics, like what
happens when you iterate over different objects!)
http://www.dabeaz.com/generators-uk/
(its the PDF presentation)
Stefan
_______________________________________________
Tutor maillist - Tutor@[...].org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor
Thread:
Spir
Hugo Arts
Spir
Hugo Arts
Stefan Lesicnik
|