ASPN ActiveState Programmer Network
ActiveState
/ Home / Perl / PHP / Python / Tcl / XSLT /
/ Safari / My ASPN /
Cookbooks | Documentation | Mailing Lists | Modules | News Feeds | Products | User Groups


Recent Messages
List Archives
About the List
List Leaders
Subscription Options

View Subscriptions
Help

View by Topic
ActiveState
.NET Framework
Open Source
Perl
PHP
Python
Tcl
Web Services
XML & XSLT

View by Category
Database
General
SOAP
System Administration
Tools
User Interfaces
Web Programming
XML Programming


MyASPN >> Mail Archive >> python-tutor
python-tutor
Re: [Tutor] PolyRange -- iterator
by Hugo Arts other posts by this author
Nov 4 2009 9:29AM messages near this date
[Tutor] PolyRange -- iterator | Re: [Tutor] PolyRange -- iterator -- PS
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 wit
h wholes in it. This whole stuff again to cope with unicode -- a poly-range would be able to
 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 "un
ite" 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' op
erator -- 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 res
ult 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

Hugo
_______________________________________________
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

Privacy Policy | Email Opt-out | Feedback | Syndication
© ActiveState Software Inc. All rights reserved