new.instancemethod __iter__

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sun Feb 7 00:35:11 CET 2010


On Sat, 06 Feb 2010 23:53:53 +0100, Martin Drautzburg wrote:

> Hello all
> 
> When I create an Object and set its __iter__ method from outside
> 
> s = Sequence #one of my own classes
> s.__iter__ = new.instancemethod(f,s,Sequence)

I'm confused as to why you are aliasing your class before changing it. 
The above just makes s an alternative name for Sequence.

Did you mean this?

s = Sequence() # make an instance of the class


> I get different results, depending on whether I call
> 
> 
> for x in y.__iter__():
>     print x

What's y? Where does it come from? Is y supposed to be an instance of 
Sequence?


> or
> 
> for x in y:
>     print x
> 
> The first case does what I expected, i.e. it iterates over whatever f()
> yields. In the second case nothing is printed. I have the impression
> that it still calls the original __iter__() method (the one defined at
> the class level).

Yes, that's almost certainly what is happening. As an optimization, 
Python bypasses the instance for special methods __NAME__.


> Why is that so?
> How can I replace the __iter__() method so it does what I want.

The best solution is, find another way to do what you want.

The clunky solution is to use delegation to wrap your class, and have the 
outer class re-direct calls to special methods to the instance first.

 
> The reason I want to do such things is I need to implement operations
> similar to what itertools do. However I want my own classes and the
> operations are only similar to itertools, but differ in significant
> details.

I don't understand this.

If you want iterator operations "similar to itertools", why does this 
mean you need to replace anything? Just create your own iterators.

Or use pre-processing and post-processing to get what you want.

Can you show an example of what you would like to happen?



-- 
Steven



More information about the Python-list mailing list