Conditionally implementing __iter__ in new style classes

infidel saint.infidel at gmail.com
Wed Jul 6 12:24:47 EDT 2005


Something like this:

>>> class Base(object):
... 	def __getitem__(self, key):
... 		return key
... 	def __iter__(self):
... 		yield self[1]
... 		yield self['foo']
... 		yield self[3.0]
...
>>> class ConcreteIterable(Base):
... 	def __iter__(self):
... 		yield True
... 		yield 'Blue'
... 		yield 'Foo'
...
>>> class ConcreteNotIterable(Base):
... 	pass
...
>>> [x for x in Base()]
[1, 'foo', 3.0]
>>> [x for x in ConcreteIterable()]
[True, 'Blue', 'Foo']
>>> [x for x in ConcreteNotIterable()]
[1, 'foo', 3.0]
>>>




More information about the Python-list mailing list