Python threading?

Jeff Epler jepler at unpythonic.net
Sat Sep 28 15:25:26 EDT 2002


On Sat, Sep 28, 2002 at 06:03:57PM +0000, Bengt Richter wrote:
> Any thoughts on defining the next method with a generic *args optional arg list
> and making it visible to an executing generator function g as g.__args__ ?
> 
> g.__args__ would then just be () for current usage, and could be
> backwards-compatibly ignored as desired.

I think you can get something like this using a class.  For this solution,
you'll need to make the list visible as a parameter to the generator, or
else write it so that you derive a class for each generator, making the
generator a method.  You may also be able to work something up involving
nested functions that lets the inner function see the argument list as
a variable in the outer scope.

class ArgsGenerator:
    def __init__(self, f, *args, **kw):
	self.args = []
	self.__iter = f(self.args, *args, **kw)

    def next(self, *args):
	self.args[:] = list(args)
	return self.__iter.next()

def primes(x):
    n = 2
    while 1:
        if x: n=x[0]
        if n == -1: return
        while 1:
            composite = 0
            for d in range(2, n-1):
                if n%d == 0:
                    composite = 1
                    break
            if not composite:
                yield n
                break
            n=n+1
        n=n+1

x = ArgsGenerator(primes)
print x.next()   # 2
print x.next(8)  # 11
print x.next()   # 13
print x.next(-1) # raises StopIteration

Jeff




More information about the Python-list mailing list