473,654 Members | 3,308 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Conditionally implementing __iter__ in new style classes

I'm trying to implement __iter__ on an abstract base class while I don't
know whether subclasses support that or not.
Hope that makes sense, if not, this code should be clearer:

class Base:
def __getattr__(sel f, name):
if name == "__iter__" and hasattr(self, "Iterator") :
return self.Iterator
raise AttributeError, name

class Concrete(Base):
def Iterator(self):
yield 1
yield 2
yield 3

The idea is that if a subclass of Base defines an 'Iterator' method,
instances are iterable. They are not iterable otherwise.

The above gives the expected behaviour: iter(Base()) raises a
"TypeError: iteration over non-sequence", and iter(Concrete() ) returns a
generator.

If, however, I make Base a newstyle class, this will not work any
longer. __getattr__ is never called for "__iter__" (neither is
__getattribute_ _, btw). Probably this has to do with data descriptors
and non-data descriptors, but I'm too tired at the moment to think
further about this.

Is there any way I could make the above code work with new style
classes?

Thanks,

Thomas

Jul 21 '05 #1
13 1937
Thomas Heller <th*****@python .net> writes:
I'm trying to implement __iter__ on an abstract base class while I don't
know whether subclasses support that or not.
Hope that makes sense, if not, this code should be clearer:

class Base:
def __getattr__(sel f, name):
if name == "__iter__" and hasattr(self, "Iterator") :
return self.Iterator
raise AttributeError, name

class Concrete(Base):
def Iterator(self):
yield 1
yield 2
yield 3

The idea is that if a subclass of Base defines an 'Iterator' method,
instances are iterable. They are not iterable otherwise.

The above gives the expected behaviour: iter(Base()) raises a
"TypeError: iteration over non-sequence", and iter(Concrete() ) returns a
generator.

If, however, I make Base a newstyle class, this will not work any
longer. __getattr__ is never called for "__iter__" (neither is
__getattribute_ _, btw). Probably this has to do with data descriptors
and non-data descriptors, but I'm too tired at the moment to think
further about this.

Is there any way I could make the above code work with new style
classes?


I forgot to mention this: The Base class also implements a __getitem__
method which should be used for iteration if the .Iterator method in the
subclass is not available. So it seems impossible to raise an exception
in the __iter__ method if .Iterator is not found - __iter__ MUST return
an iterator if present.

Thomas
Jul 21 '05 #2
> I'm trying to implement __iter__ on an abstract base class while I
don't
know whether subclasses support that or not.
Hope that makes sense, if not, this code should be clearer:

class Base:
def __getattr__(sel f, name):
if name == "__iter__" and hasattr(self, "Iterator") :
return self.Iterator
raise AttributeError, name

class Concrete(Base):
def Iterator(self):
yield 1
yield 2
yield 3


I don't know how to achieve it, but why don't you simply use

class Base:
pass

class Concrete(Base):
def __iter__(self) :
yield 1
yield 2
yield 3
What is the advantage to have a baseclass that essentially does
some method renaming __iter__ ==> Iterator?

- harold -

--
Always remember that you are unique;
just like everyone else.
--

Jul 21 '05 #3
I'm not sure I understand why you would want to. Just don't define
__iter__ on your newstyle class and you'll get the expected behavior.

Jul 21 '05 #4
Why not define an Iterator method in your Base class that does the
iteration using __getitem__, and any subclass that wants to do
something else just defines its own Iterator method? For that matter,
you could just use the __iter__ methods of Base and Concrete instead of
a separate method.

Jul 21 '05 #5
Something like this:
class Base(object): .... def __getitem__(sel f, key):
.... return key
.... def __iter__(self):
.... yield self[1]
.... yield self['foo']
.... yield self[3.0]
.... class ConcreteIterabl e(Base): .... def __iter__(self):
.... yield True
.... yield 'Blue'
.... yield 'Foo'
.... class ConcreteNotIter able(Base): .... pass
.... [x for x in Base()] [1, 'foo', 3.0] [x for x in ConcreteIterabl e()] [True, 'Blue', 'Foo'] [x for x in ConcreteNotIter able()] [1, 'foo', 3.0]


Jul 21 '05 #6
Thomas Heller wrote:
I forgot to mention this: The Base class also implements a __getitem__
method which should be used for iteration if the .Iterator method in the
subclass is not available. So it seems impossible to raise an exception
in the __iter__ method if .Iterator is not found - __iter__ MUST return
an iterator if present.


def Iterator(self):
for index in xrange(len(self )):
yield self[index]

def __iter__(self):
return self.Iterator()

....and then override Iterator in subclasses. But this raises the
question of why you need to use a specially-named method instead of
having subclasses override the __iter__.
Jul 21 '05 #7
Thomas Heller wrote:
I'm trying to implement __iter__ on an abstract base class while I don't
know whether subclasses support that or not.
Hope that makes sense, if not, this code should be clearer:

class Base:
def __getattr__(sel f, name):
if name == "__iter__" and hasattr(self, "Iterator") :
return self.Iterator
raise AttributeError, name Is there any way I could make the above code work with new style
classes?


Obligatory metaclass approach:

class Base:
class __metaclass__(t ype):
def __new__(mcl, name, bases, classdict):
try:
classdict["__iter__"] = classdict["Iterator"]
except KeyError:
pass
return type.__new__(mc l, name, bases, classdict)

class Alpha(Base):
def Iterator(self): yield 42

class Beta(Base):
def __getitem__(sel f, index):
return [1, 2, 3, "ganz viele"][index]
for item in Alpha(): print item
for item in Beta(): print item,
print

Peter

Jul 21 '05 #8
On Wed, 06 Jul 2005 17:57:42 +0200, Thomas Heller <th*****@python .net> wrote:
I'm trying to implement __iter__ on an abstract base class while I don't
know whether subclasses support that or not.
Hope that makes sense, if not, this code should be clearer:

class Base:
def __getattr__(sel f, name):
if name == "__iter__" and hasattr(self, "Iterator") :
return self.Iterator
raise AttributeError, name

class Concrete(Base):
def Iterator(self):
yield 1
yield 2
yield 3

The idea is that if a subclass of Base defines an 'Iterator' method,
instances are iterable. They are not iterable otherwise.

The above gives the expected behaviour: iter(Base()) raises a
"TypeError: iteration over non-sequence", and iter(Concrete() ) returns a
generator.

If, however, I make Base a newstyle class, this will not work any
longer. __getattr__ is never called for "__iter__" (neither is
__getattribute __, btw). Probably this has to do with data descriptors
and non-data descriptors, but I'm too tired at the moment to think
further about this.

Is there any way I could make the above code work with new style
classes?

Will a property or custom descriptor do what you want? E.g.
class Base(object): ... def __getIter(self) :
... if hasattr(self, "Iterator") :
... return self.Iterator
... raise AttributeError, name
... __iter__ = property(__getI ter)
... class Concrete(Base): ... def Iterator(self):
... yield 1
... yield 2
... yield 3
... iter(Base()) Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: iteration over non-sequence iter(Concrete() ) <generator object at 0x02EF152C> list(iter(Concr ete()))

[1, 2, 3]

Regards,
Bengt Richter
Jul 21 '05 #9
bo**@oz.net (Bengt Richter) writes:
On Wed, 06 Jul 2005 17:57:42 +0200, Thomas Heller <th*****@python .net> wrote:
I'm trying to implement __iter__ on an abstract base class while I don't
know whether subclasses support that or not.
Will a property or custom descriptor do what you want? E.g.
>>> class Base(object): ... def __getIter(self) :
... if hasattr(self, "Iterator") :
... return self.Iterator
... raise AttributeError, name
... __iter__ = property(__getI ter)
... >>> class Concrete(Base): ... def Iterator(self):
... yield 1
... yield 2
... yield 3
... >>> iter(Base()) Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: iteration over non-sequence >>> iter(Concrete() ) <generator object at 0x02EF152C> >>> list(iter(Concr ete()))

[1, 2, 3]


Yep, that's exactly what I need - thanks.

Thomas
Jul 21 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
1738
by: adeleinandjeremy | last post by:
I am taking a second programming course in Java and am currently attempting to apply what I have learned using Python instead. One thing that is puzzling me is how to use an iterator. I am writing a module containing everything I'd need for canonical linked lists. One particularly useful feature would be to use a for loop over the whole structure. For this I have learned the benefits of iterators. I have read a few book entries on Python...
3
5619
by: Adelein and Jeremy | last post by:
I am taking a second programming course in Java and am currently attempting to apply what I have learned using Python instead. One thing that is puzzling me is how to use an iterator. I am writing a module containing everything I'd need for canonical linked lists. One particularly useful feature would be to use a for loop over the whole structure. For this I have learned the benefits of iterators. I have read a few book entries on...
21
2059
by: Steven Bethard | last post by:
Can someone point me to the documentation on what's supposed to happen when you use the "for x in X:" syntax when X does not have an __iter__ method? I know that the code: >>> class S: .... def __len__(self): return 42 .... def __getitem__(self, i): return i .... >>> for x in S(): .... print x
8
2564
by: Steven Bethard | last post by:
Sorry if this is a repost -- it didn't appear for me the first time. So I was looking at the Language Reference's discussion about emulating container types, and nowhere in it does it mention that .keys() is part of the container protocol. Because of this, I would assume that to use UserDict.DictMixin correctly, a class would only need to define __getitem__, __setitem__, __delitem__ and __iter__. So why does UserDict.DictMixin...
3
1720
by: alwayswinter | last post by:
I currently have a form where a user can enter results from a genetic test. I also have a pool of summaries that would correspond to different results that a user would enter into the form. I ideally I would like to have the user enter their results and then have a master summary created with the different word or HTML files on submit. (condition 1 + condition 2 = combining/displaying corresponding HTML files) I've gotten as far as...
1
1051
by: Noah Subrin | last post by:
Hello, I have a class like the following public class person public FirstName as string public LastName as string end class
4
3323
by: phl | last post by:
hi, My question is: 1. To avoid possible memory leaks, when you use this pattern, after you have dealth with the unmanaged resources and before you take your object off the finalize queue, how are you sure that your managed object resources are completely freed up of resources it's might be using? In my case below I have a private bool variable. Are there any other managed resource that you might need to explicitly free up in
10
2299
by: mrquantum | last post by:
Hello! Just for curiosity i'd like to know why strings don't support the iteration protocoll!? Is there some deeper reason for this? False In Python 2.5 it's actually simple to obtain one: 'S'
2
2336
by: IloChab | last post by:
I'd like to implement an object that represents a circular counter, i.e. an integer that returns to zero when it goes over it's maxVal. This counter has a particular behavior in comparison: if I compare two of them an they differ less than half of maxVal I want that, for example, 0 maxVal gives true. This is because my different counters grew together and they never differ a lot between them and so a value of 0 compared with an other of...
0
8379
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8294
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8816
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8709
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8494
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7309
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5627
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
2719
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1597
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.