[Edu-sig] Scratch pad nuttiness... (re generators)

kirby urner kirby.urner at gmail.com
Mon Mar 16 16:42:24 CET 2009


So per the blog post below, I'm explaining the Python generator
concept in terms of "kicking the can down the road" e.g. getting the
next prime in some "just in time" trial by division regimen, per
archived examples.

http://worldgame.blogspot.com/2009/01/more-geometric-studies.html

So then it occurs to me, would there by a way to do a kind of special
names overloading such that __next__ (that which triggers the next
cycling to yield) might be replaced with the word kick in some
namespace, as in kick(o) instead of next(o) -- using Python 3.x syntax
here i.e. not o.next().

What would a student try, if this were the challenge?

Simple solution:

>>> def kick(o):
	return next(o)

>>> def f():  # could use a generator expression
	for i in range(10):
		yield i

		
>>> type(f)  # just a function so far
<class 'function'>
>>> o = f()
>>> next(o)
0
>>> kick(o)
1
>>> kick(o)
2
>>> type(o)  # a generator once instanced
<class 'generator'>

Another student might think different and try something like this:

>>> o.__next__
<method-wrapper '__next__' of generator object at 0x8367edc>
>>> o.kick = o.__next__
Traceback (most recent call last):
  File "<pyshell#51>", line 1, in <module>
    o.kick = o.__next__
AttributeError: 'generator' object has no attribute 'kick'

"Dang, you can't give your generator object a random attribute it
doesn't already have, write-protected in some way...."

Note that the generator type is inappropriate as a base class for your
own kind of user class.

>>> class newgen (type(o)):
	kick = type(o).__next__

	
Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    class newgen (type(o)):
TypeError: type 'generator' is not an acceptable base type

Oh well....

Kirby


More information about the Edu-sig mailing list