Commits

Antoine Boegli committed 83bfc9b

Begin of the upgrade of candygram to New Style Classes and threading.Thread and Lock

Comments (0)

Files changed (30)

examples/priority_receiver.py

+# -*- coding: utf-8 -*-
 # I hereby disclaim all copyright to the contents of this file,
 # priority_receiver.py, and place it into the public domain.
 #   -- Michael Hobbs
 
 
 def timeout():
-	return TIMEOUT
+    return TIMEOUT
 
 
-class PriorityReceiver:
-	def __init__(self, receivers):
-		self.__receivers = []
-		prevReceiver = None
-		for receiver in receivers:
-			mergedReceiver = Receiver()
-			if prevReceiver is not None:
-				mergedReceiver.addHandlers(prevReceiver)
-			mergedReceiver.addHandlers(receiver)
-			self.__receivers.append(mergedReceiver)
-			prevReceiver = mergedReceiver
-		# end for
+class PriorityReceiver(object):
+    def __init__(self, receivers):
+        self.__receivers = []
+        prevReceiver = None
+        for receiver in receivers:
+            mergedReceiver = Receiver()
+            if prevReceiver is not None:
+                mergedReceiver.addHandlers(prevReceiver)
+            mergedReceiver.addHandlers(receiver)
+            self.__receivers.append(mergedReceiver)
+            prevReceiver = mergedReceiver
+        # end for
 
-	def receive(self, *args, **kwargs):
-		for receiver in self.__receivers[:-1]:
-			result = receiver.receive(0, timeout)
-			if result is not TIMEOUT:
-				return result
-			# end if
-		return self.__receivers[-1].receive(*args, **kwargs)
+    def receive(self, *args, **kwargs):
+        for receiver in self.__receivers[:-1]:
+            result = receiver.receive(0, timeout)
+            if result is not TIMEOUT:
+                return result
+            # end if
+        return self.__receivers[-1].receive(*args, **kwargs)
 
-	__call__ = receive
-	next = receive
+    __call__ = receive
+    next = receive
 
-	def __iter__(self):
-		return self
+    def __iter__(self):
+        return self

examples/program_5.1.py

 
 
 def start():
-	return spawn(loop, 0)
+    return spawn(loop, 0)
 
 
 def loop(val):
-	r = Receiver()
-	r['increment'] = loop, val + 1
-	return r()
+    r = Receiver()
+    r['increment'] = loop, val + 1
+    return r()

examples/program_5.1_alt.py

+# -*- coding: utf-8 -*-
 # I hereby disclaim all copyright to the contents of this file,
 # program_5.1_alt.py, and place it into the public domain.
 #   -- Michael Hobbs
 
 
 def start():
-	loop = Loop()
-	return spawn(loop.loop)
+    loop = Loop()
+    return spawn(loop.loop)
 
 
-class Loop:
-	def __init__(self):
-		self.val = 0
+class Loop(object):
+    def __init__(self):
+        self.val = 0
 
-	def increment(self):
-		self.val += 1
+    def increment(self):
+        self.val += 1
 
-	def loop(self):
-		r = Receiver()
-		r.addHandler('increment', self.increment)
-		for _ in r:
-			pass
-		# end for
+    def loop(self):
+        r = Receiver()
+        r.addHandler('increment', self.increment)
+        for _ in r:
+            pass
+        # end for

examples/program_5.2.py

 
 # First the interface functions.
 def start():
-	return spawn(loop, 0)
+    return spawn(loop, 0)
 
 
 def increment(counter):
-	return counter | 'increment'
+    return counter | 'increment'
 
 
 def value(counter):
-	counter | (self(),'value')
-	r = Receiver()
-	r[counter, int] = lambda msg: msg[1], Message
-	return r()
+    counter | (self(),'value')
+    r = Receiver()
+    r[counter, int] = lambda msg: msg[1], Message
+    return r()
 
 
 def stop(counter):
-	return counter | 'stop'
+    return counter | 'stop'
 
 
 # The counter loop.
 def loop(val):
-	r = Receiver()
-	r['increment'] = loop, val + 1
-	def sendVal(msg):
-		from_, _ = msg
-		from_ | (self(),val)
-		return loop(val)
-	r[Process, 'value'] = sendVal, Message
-	r['stop'] = lambda: True  # No recursive call here
-	r[Any] = loop, val  # All other messages
-	return r()
+    r = Receiver()
+    r['increment'] = loop, val + 1
+    def sendVal(msg):
+        from_, _ = msg
+        from_ | (self(),val)
+        return loop(val)
+    r[Process, 'value'] = sendVal, Message
+    r['stop'] = lambda: True  # No recursive call here
+    r[Any] = loop, val  # All other messages
+    return r()

examples/program_5.2_alt.py

+# -*- coding: utf-8 -*-
 # I hereby disclaim all copyright to the contents of this file,
 # program_5.2_alt.py, and place it into the public domain.
 #   -- Michael Hobbs
 
 # First the interface functions.
 def start():
-	loop = Loop()
-	return spawn(loop.loop)
+    loop = Loop()
+    return spawn(loop.loop)
 
 
 def increment(counter):
-	return counter.send('increment')
+    return counter.send('increment')
 
 
 def value(counter):
-	counter.send((self(),'value'))
-	r = Receiver()
-	r.addHandler((counter, int), lambda msg: msg[1], Message)
-	return r.receive()
+    counter.send((self(),'value'))
+    r = Receiver()
+    r.addHandler((counter, int), lambda msg: msg[1], Message)
+    return r.receive()
 
 
 def stop(counter):
-	return counter.send('stop')
+    return counter.send('stop')
 
 
 # The counter loop.
-class Loop:
-	def __init__(self):
-		self.val = 0
-		self.stop = False
+class Loop(object):
+    def __init__(self):
+        self.val = 0
+        self.stop = False
 
-	def increment(self):
-		self.val += 1
+    def increment(self):
+        self.val += 1
 
-	def sendVal(self, msg):
-		from_, _ = msg
-		from_.send((self_(),self.val))
+    def sendVal(self, msg):
+        from_, _ = msg
+        from_.send((self_(),self.val))
 
-	def stopFunc(self):
-		self.stop = True
+    def stopFunc(self):
+        self.stop = True
 
-	def loop(self):
-		r = Receiver()
-		r.addHandler('increment', self.increment)
-		r.addHandler((Process, 'value'), self.sendVal, Message)
-		r.addHandler('stop', self.stopFunc)
-		r.addHandler(Any)  # All other messages
-		for _ in r:
-			if self.stop:
-				break
-			# end if
-		return True
+    def loop(self):
+        r = Receiver()
+        r.addHandler('increment', self.increment)
+        r.addHandler((Process, 'value'), self.sendVal, Message)
+        r.addHandler('stop', self.stopFunc)
+        r.addHandler(Any)  # All other messages
+        for _ in r:
+            if self.stop:
+                break
+            # end if
+        return True

examples/program_5.3.py

 
 
 def s1():
-	r = Receiver()
-	r['msg_a'] = s2
-	r['msg_c'] = s3
-	return r()
+    r = Receiver()
+    r['msg_a'] = s2
+    r['msg_c'] = s3
+    return r()
 
 
 def s2():
-	r = Receiver()
-	r['msg_x'] = s3
-	r['msg_h'] = s4
-	return r()
+    r = Receiver()
+    r['msg_x'] = s3
+    r['msg_h'] = s4
+    return r()
 
 
 def s3():
-	r = Receiver()
-	r['msg_b'] = s1
-	r['msg_y'] = s2
-	return r()
+    r = Receiver()
+    r['msg_b'] = s1
+    r['msg_y'] = s2
+    return r()
 
 
 def s4():
-	r = Receiver()
-	r['msg_i'] = s3
-	return r()
+    r = Receiver()
+    r['msg_i'] = s3
+    return r()

examples/program_5.3_alt.py

 
 
 def s1():
-	s1 = Receiver()
-	s2 = Receiver()
-	s3 = Receiver()
-	s4 = Receiver()
-	s1.addHandler('msg_a', lambda: s2)
-	s1.addHandler('msg_c', lambda: s3)
-	s2.addHandler('msg_x', lambda: s3)
-	s2.addHandler('msg_h', lambda: s4)
-	s3.addHandler('msg_b', lambda: s1)
-	s3.addHandler('msg_y', lambda: s2)
-	s4.addHandler('msg_i', lambda: s3)
-	r = s1
-	while True:
-		r = r.receive()
-	# end while
+    s1 = Receiver()
+    s2 = Receiver()
+    s3 = Receiver()
+    s4 = Receiver()
+    s1.addHandler('msg_a', lambda: s2)
+    s1.addHandler('msg_c', lambda: s3)
+    s2.addHandler('msg_x', lambda: s3)
+    s2.addHandler('msg_h', lambda: s4)
+    s3.addHandler('msg_b', lambda: s1)
+    s3.addHandler('msg_y', lambda: s2)
+    s4.addHandler('msg_i', lambda: s3)
+    r = s1
+    while True:
+        r = r.receive()
+    # end while

examples/program_5.4.py

 
 
 def timeout(time, alarm):
-	return spawn(timer, self(), time, alarm)
+    return spawn(timer, self(), time, alarm)
 
 
 def cancel(timer):
-	return timer | (self(),'cancel')
+    return timer | (self(),'cancel')
 
 
 def timer(pid, time, alarm):
-	r = Receiver()
-	r[Process, 'cancel'] = lambda: True
-	return r(time, lambda: pid | alarm)
+    r = Receiver()
+    r[Process, 'cancel'] = lambda: True
+    return r(time, lambda: pid | alarm)

examples/program_5.4_alt.py

+# -*- coding: utf-8 -*-
 # I hereby disclaim all copyright to the contents of this file,
 # program_5.4_alt.py, and place it into the public domain.
 #   -- Michael Hobbs
 
 
 def timeout(time, alarm):
-	timer = Timer(self(), time, alarm)
-	return spawn(timer.timer)
+    timer = Timer(self(), time, alarm)
+    return spawn(timer.timer)
 
 
 def cancel(timer):
-	return timer.send((self(),'cancel'))
+    return timer.send((self(),'cancel'))
 
 
-class Timer:
-	def __init__(self, pid, time, alarm):
-		self.pid = pid
-		self.time = time
-		self.alarm = alarm
+class Timer(object):
+    def __init__(self, pid, time, alarm):
+        self.pid = pid
+        self.time = time
+        self.alarm = alarm
 
-	def timeout(self):
-		self.pid.send(self.alarm)
+    def timeout(self):
+        self.pid.send(self.alarm)
 
-	def timer(self):
-		r = Receiver()
-		r.addHandler((Process, 'cancel'))
-		r.after(self.time, self.timeout)
-		r.receive()
+    def timer(self):
+        r = Receiver()
+        r.addHandler((Process, 'cancel'))
+        r.after(self.time, self.timeout)
+        r.receive()

examples/program_5.5.py

 
 
 def start():
-	global number_analyser
-	number_analyser = spawn(server, {})
-	return number_analyser
+    global number_analyser
+    number_analyser = spawn(server, {})
+    return number_analyser
 
 
 # The interface functions.
 def add_number(seq, dest):
-	return request(('add_number',seq,dest))
+    return request(('add_number',seq,dest))
 
 
 def analyse(seq):
-	return request(('analyse',seq))
+    return request(('analyse',seq))
 
 
 def request(req):
-	number_analyser | (self(), req)
-	r = Receiver()
-	r[number_analyser,Any] = lambda msg: msg[1], Message
-	return r()
+    number_analyser | (self(), req)
+    r = Receiver()
+    r[number_analyser,Any] = lambda msg: msg[1], Message
+    return r()
 
 
 # The server.
 def server(analTable):
-	r = Receiver()
-	def sendAnal(msg):
-		from_, (_, seq) = msg
-		result = analTable.get(seq, None)
-		from_ | (number_analyser, result)
-		return server(analTable)
-	r[Process, ('analyse',str)] = sendAnal, Message
-	def sendAck(msg):
-		from_, (_, seq, dest) = msg
-		from_ | (number_analyser, 'ack')
-		analTable[seq] = dest
-		return server(analTable)
-	r[Process, ('add_number', str, Any)] = sendAck, Message
-	return r()
+    r = Receiver()
+    def sendAnal(msg):
+        from_, (_, seq) = msg
+        result = analTable.get(seq, None)
+        from_ | (number_analyser, result)
+        return server(analTable)
+    r[Process, ('analyse',str)] = sendAnal, Message
+    def sendAck(msg):
+        from_, (_, seq, dest) = msg
+        from_ | (number_analyser, 'ack')
+        analTable[seq] = dest
+        return server(analTable)
+    r[Process, ('add_number', str, Any)] = sendAck, Message
+    return r()

examples/program_5.5_alt.py

+# -*- coding: utf-8 -*-
 # I hereby disclaim all copyright to the contents of this file,
 # program_5.5_alt.py, and place it into the public domain.
 #   -- Michael Hobbs
 
 
 def start():
-	global number_analyser
-	server = Server({})
-	number_analyser = spawn(server.server)
-	return number_analyser
+    global number_analyser
+    server = Server({})
+    number_analyser = spawn(server.server)
+    return number_analyser
 
 
 # The interface functions.
 def add_number(seq, dest):
-	return request(('add_number',seq,dest))
+    return request(('add_number',seq,dest))
 
 
 def analyse(seq):
-	return request(('analyse',seq))
+    return request(('analyse',seq))
 
 
 def request(req):
-	number_analyser.send((self(), req))
-	r = Receiver()
-	r.addHandler((number_analyser,Any), lambda msg: msg[1], Message)
-	return r.receive()
+    number_analyser.send((self(), req))
+    r = Receiver()
+    r.addHandler((number_analyser,Any), lambda msg: msg[1], Message)
+    return r.receive()
 
 
 # The server.
-class Server:
-	def __init__(self, analTable):
-		self.analTable = analTable
+class Server(object):
+    def __init__(self, analTable):
+        self.analTable = analTable
 
-	def sendAnal(self, msg):
-		from_, (_, seq) = msg
-		result = self.analTable.get(seq, None)
-		from_.send((number_analyser, result))
+    def sendAnal(self, msg):
+        from_, (_, seq) = msg
+        result = self.analTable.get(seq, None)
+        from_.send((number_analyser, result))
 
-	def sendAck(self, msg):
-		from_, (_, seq, dest) = msg
-		from_.send((number_analyser, 'ack'))
-		self.analTable[seq] = dest
+    def sendAck(self, msg):
+        from_, (_, seq, dest) = msg
+        from_.send((number_analyser, 'ack'))
+        self.analTable[seq] = dest
 
-	def server(self):
-		r = Receiver()
-		r.addHandler((Process, ('analyse',str)), self.sendAnal, Message)
-		r.addHandler((Process, ('add_number', str, Any)), self.sendAck, Message)
-		for _ in r:
-			pass
-		return True
+    def server(self):
+        r = Receiver()
+        r.addHandler((Process, ('analyse',str)), self.sendAnal, Message)
+        r.addHandler((Process, ('add_number', str, Any)), self.sendAck, Message)
+        for _ in r:
+            pass
+        return True

examples/program_5.6.py

 
 
 def start(resources):
-	global resource_alloc
-	pid = spawn(server, resources, [])
-	resource_alloc = pid
-	return pid
+    global resource_alloc
+    pid = spawn(server, resources, [])
+    resource_alloc = pid
+    return pid
 
 
 # The interface functions.
 def allocate():
-	return request('alloc')
+    return request('alloc')
 
 
 def free(resource):
-	return request(('free',resource))
+    return request(('free',resource))
 
 
 def request(req):
-	resource_alloc | (self(),req)
-	r = Receiver()
-	r[resource_alloc,Any] = lambda msg: msg[1], Message
-	return r()
+    resource_alloc | (self(),req)
+    r = Receiver()
+    r[resource_alloc,Any] = lambda msg: msg[1], Message
+    return r()
 
 
 # The server.
 def server(free, allocated):
-	r = Receiver()
-	r[Process,'alloc'] = allocate_, free, allocated, Message
-	r[Process,('free',Any)] = free_, free, allocated, Message
-	return r()
+    r = Receiver()
+    r[Process,'alloc'] = allocate_, free, allocated, Message
+    r[Process,('free',Any)] = free_, free, allocated, Message
+    return r()
 
 
 def allocate_(free, allocated, msg):
-	from_, _ = msg
-	if free:
-		r, free = free[0], free[1:]
-		from_ | (resource_alloc,('yes',r))
-		allocated.insert(0, (r,from_))
-		return server(free, allocated)
-	from_ | (resource_alloc,'no')
-	return server([], allocated)
+    from_, _ = msg
+    if free:
+        r, free = free[0], free[1:]
+        from_ | (resource_alloc,('yes',r))
+        allocated.insert(0, (r,from_))
+        return server(free, allocated)
+    from_ | (resource_alloc,'no')
+    return server([], allocated)
 
 
 def free_(free, allocated, msg):
-	from_, (_, r) = msg
-	if (r,from_) in allocated:
-		from_ | (resource_alloc,'ok')
-		free.insert(0, r)
-		allocated.remove((r,from_))
-		return server(free, allocated)
-	else:
-		from_ | (resource_alloc,'error')
-		return server(free, allocated)
-	# end if
+    from_, (_, r) = msg
+    if (r,from_) in allocated:
+        from_ | (resource_alloc,'ok')
+        free.insert(0, r)
+        allocated.remove((r,from_))
+        return server(free, allocated)
+    else:
+        from_ | (resource_alloc,'error')
+        return server(free, allocated)
+    # end if

examples/program_5.6_alt.py

+# -*- coding: utf-8 -*-
 # I hereby disclaim all copyright to the contents of this file,
 # program_5.6_alt.py, and place it into the public domain.
 #   -- Michael Hobbs
 
 
 def start(resources):
-	global resource_alloc
-	server = Server(resources, [])
-	pid = spawn(server.server)
-	resource_alloc = pid
-	return pid
+    global resource_alloc
+    server = Server(resources, [])
+    pid = spawn(server.server)
+    resource_alloc = pid
+    return pid
 
 
 # The interface functions.
 def allocate():
-	return request('alloc')
+    return request('alloc')
 
 
 def free(resource):
-	return request(('free',resource))
+    return request(('free',resource))
 
 
 def request(req):
-	resource_alloc.send((self(),req))
-	r = Receiver()
-	r.addHandler((resource_alloc,Any), lambda msg: msg[1], Message)
-	return r.receive()
+    resource_alloc.send((self(),req))
+    r = Receiver()
+    r.addHandler((resource_alloc,Any), lambda msg: msg[1], Message)
+    return r.receive()
 
 
 # The server.
-class Server:
-	def __init__(self, free, allocated):
-		self.free = free
-		self.allocated = allocated
+class Server(object):
+    def __init__(self, free, allocated):
+        self.free = free
+        self.allocated = allocated
 
-	def server(self):
-		r = Receiver()
-		r.addHandler((Process,'alloc'), self.allocate, Message)
-		r.addHandler((Process,('free',Any)), self.free_, Message)
-		for _ in r:
-			pass
-		return True
+    def server(self):
+        r = Receiver()
+        r.addHandler((Process,'alloc'), self.allocate, Message)
+        r.addHandler((Process,('free',Any)), self.free_, Message)
+        for _ in r:
+            pass
+        return True
 
-	def allocate(self, msg):
-		from_, _ = msg
-		if self.free:
-			r, self.free = self.free[0], self.free[1:]
-			from_.send((resource_alloc,('yes',r)))
-			self.allocated.insert(0, (r,from_))
-		else:
-			from_.send((resource_alloc,'no'))
-		# end if
+    def allocate(self, msg):
+        from_, _ = msg
+        if self.free:
+            r, self.free = self.free[0], self.free[1:]
+            from_.send((resource_alloc,('yes',r)))
+            self.allocated.insert(0, (r,from_))
+        else:
+            from_.send((resource_alloc,'no'))
+        # end if
 
-	def free_(self, msg):
-		from_, (_, r) = msg
-		if (r,from_) in self.allocated:
-			from_.send((resource_alloc,'ok'))
-			self.free.insert(0, r)
-			self.allocated.remove((r,from_))
-		else:
-			from_.send((resource_alloc,'error'))
-		# end if
+    def free_(self, msg):
+        from_, (_, r) = msg
+        if (r,from_) in self.allocated:
+            from_.send((resource_alloc,'ok'))
+            self.free.insert(0, r)
+            self.allocated.remove((r,from_))
+        else:
+            from_.send((resource_alloc,'error'))
+        # end if

examples/program_7.1.py

 
 
 def start():
-	global my_name
-	my_name = spawn(process)
-	return my_name
+    global my_name
+    my_name = spawn(process)
+    return my_name
 
 
 def process():
-	r = Receiver()
-	def stop(msg):
-		_, method = msg
-		if method == 'return':
-			return True
-		else:
-			exit('normal')
-		# end if
-	r['stop', Any] = stop, Message
-	r[Any] = process
-	return r()
+    r = Receiver()
+    def stop(msg):
+        _, method = msg
+        if method == 'return':
+            return True
+        else:
+            exit('normal')
+        # end if
+    r['stop', Any] = stop, Message
+    r[Any] = process
+    return r()

examples/program_7.1_alt.py

+# -*- coding: utf-8 -*-
 # I hereby disclaim all copyright to the contents of this file,
 # program_7.1_alt.py, and place it into the public domain.
 #   -- Michael Hobbs
 
 
 def start():
-	global my_name
-	process = Process()
-	my_name = spawn(process.process)
-	return my_name
+    global my_name
+    process = Process()
+    my_name = spawn(process.process)
+    return my_name
 
 
-class Process:
-	def __init__(self):
-		self.stop = False
+class Process(object):
+    def __init__(self):
+        self.stop = False
 
-	def stop_(self, msg):
-		_, method = msg
-		if method == 'return':
-			self.stop = True
-		else:
-			exit('normal')
-		# end if
+    def stop_(self, msg):
+        _, method = msg
+        if method == 'return':
+            self.stop = True
+        else:
+            exit('normal')
+        # end if
 
-	def process(self):
-		r = Receiver()
-		r.addHandler(('stop', Any), self.stop_, Message)
-		r.addHandler(Any)
-		for _ in r:
-			if self.stop:
-				break
-			# end if
-		return True
+    def process(self):
+        r = Receiver()
+        r.addHandler(('stop', Any), self.stop_, Message)
+        r.addHandler(Any)
+        for _ in r:
+            if self.stop:
+                break
+            # end if
+        return True

examples/program_7.2.py

 
 
 def start(n):
-	global start_
-	start_ = spawnLink(p1, n - 1)
-	return start_
+    global start_
+    start_ = spawnLink(p1, n - 1)
+    return start_
 
 
 def p1(n):
-	if n == 0:
-		return top1()
-	return top(spawnLink(p1, n - 1),n)
+    if n == 0:
+        return top1()
+    return top(spawnLink(p1, n - 1),n)
 
 
 def top(next, n):
-	r = Receiver()
-	def fun(x):
-		next | x
-		print 'Process %s received %s' % (n, x)
-		return top(next,n)
-	r[Any] = fun, Message
-	return r()
+    r = Receiver()
+    def fun(x):
+        next | x
+        print 'Process %s received %s' % (n, x)
+        return top(next,n)
+    r[Any] = fun, Message
+    return r()
 
 
 def top1():
-	r = Receiver()
-	def stop():
-		print 'Last process now exiting '
-		exit('finished')
-	r['stop'] = stop
-	def fun(x):
-		print 'Last process received %s' % x
-		return top1()
-	r[Any] = fun, Message
-	return r()
+    r = Receiver()
+    def stop():
+        print 'Last process now exiting '
+        exit('finished')
+    r['stop'] = stop
+    def fun(x):
+        print 'Last process received %s' % x
+        return top1()
+    r[Any] = fun, Message
+    return r()
 
 
 def test(mess):
-	return start_ | mess
+    return start_ | mess

examples/program_7.2_alt.py

+# -*- coding: utf-8 -*-
 # I hereby disclaim all copyright to the contents of this file,
 # program_7.2_alt.py, and place it into the public domain.
 #   -- Michael Hobbs
 
 
 def start(n):
-	global start_
-	start_ = p1(n)
-	return start_
+    global start_
+    start_ = p1(n)
+    return start_
 
 
 def p1(n):
-	next = None
-	for i in range(n):
-		if i == 0:
-			top = Top1()
-		else:
-			top = Top(next, i)
-		next = spawn(top.top)
-	link(next)
-	return next
+    next = None
+    for i in range(n):
+        if i == 0:
+            top = Top1()
+        else:
+            top = Top(next, i)
+        next = spawn(top.top)
+    link(next)
+    return next
 
 
-class Top:
-	def __init__(self, next, n):
-		self.next = next
-		self.n = n
+class Top(object):
+    def __init__(self, next, n):
+        self.next = next
+        self.n = n
 
-	def fun(self, x):
-		self.next.send(x)
-		print 'Process %s received %s' % (self.n, x)
+    def fun(self, x):
+        self.next.send(x)
+        print 'Process %s received %s' % (self.n, x)
 
-	def top(self):
-		link(self.next)
-		r = Receiver()
-		r.addHandler(Any, self.fun, Message)
-		for _ in r:
-			pass
-		return True
+    def top(self):
+        link(self.next)
+        r = Receiver()
+        r.addHandler(Any, self.fun, Message)
+        for _ in r:
+            pass
+        return True
 
 
-class Top1:
-	def stop(self):
-		print 'Last process now exiting '
-		exit('finished')
+class Top1(object):
+    def stop(self):
+        print 'Last process now exiting '
+        exit('finished')
 
-	def fun(self, x):
-		print 'Last process received %s' % x
+    def fun(self, x):
+        print 'Last process received %s' % x
 
-	def top(self):
-		r = Receiver()
-		r.addHandler('stop', self.stop)
-		r.addHandler(Any, self.fun, Message)
-		for _ in r:
-			pass
-		return True
+    def top(self):
+        r = Receiver()
+        r.addHandler('stop', self.stop)
+        r.addHandler(Any, self.fun, Message)
+        for _ in r:
+            pass
+        return True
 
 
 def test(mess):
-	return start_.send(mess)
+    return start_.send(mess)

examples/program_7.3.py

 
 
 def start():
-	global demo_
-	demo_ = spawn(demo)
-	return demo_
+    global demo_
+    demo_ = spawn(demo)
+    return demo_
 
 
 def demo():
-	processFlag('trap_exit', True)
-	return demo1()
+    processFlag('trap_exit', True)
+    return demo1()
 
 
 def demo1():
-	r = Receiver()
-	def normalExit(msg):
-		_, from_, _ = msg
-		print 'Demo process received normal exit from %s' % from_
-		return demo1()
-	r['EXIT', Process, 'normal'] = normalExit, Message
-	def otherExit(msg):
-		_, from_, reason = msg
-		print 'Demo process received exit signal %s from %s' % (reason, from_)
-		return demo1()
-	r['EXIT', Process, Any] = otherExit, Message
-	def finished():
-		print 'Demo finished '
-	r['finished_demo'] = finished
-	def other(msg):
-		print 'Demo process message %s' % msg
-		return demo1()
-	r[Any] = other, Message
-	return r()
+    r = Receiver()
+    def normalExit(msg):
+        _, from_, _ = msg
+        print 'Demo process received normal exit from %s' % from_
+        return demo1()
+    r['EXIT', Process, 'normal'] = normalExit, Message
+    def otherExit(msg):
+        _, from_, reason = msg
+        print 'Demo process received exit signal %s from %s' % (reason, from_)
+        return demo1()
+    r['EXIT', Process, Any] = otherExit, Message
+    def finished():
+        print 'Demo finished '
+    r['finished_demo'] = finished
+    def other(msg):
+        print 'Demo process message %s' % msg
+        return demo1()
+    r[Any] = other, Message
+    return r()
 
 
 def demonstrate_normal():
-	def func():
-		link(demo_)
-	return spawn(func)
+    def func():
+        link(demo_)
+    return spawn(func)
 
 
 def demonstrate_exit(what):
-	def func():
-		link(demo_)
-		exit(what)
-	return spawn(func)
+    def func():
+        link(demo_)
+        exit(what)
+    return spawn(func)
 
 
 def demonstrate_message(what):
-	def func():
-		demo_ | what
-	return spawn(func)
+    def func():
+        demo_ | what
+    return spawn(func)
 
 
 def demonstrate_error():
-	def func():
-		link(demo_)
-		1 / 0
-	return spawn(func)
+    def func():
+        link(demo_)
+        1 / 0
+    return spawn(func)

examples/program_7.3_alt.py

+# -*- coding: utf-8 -*-
 # I hereby disclaim all copyright to the contents of this file,
 # program_7.3_alt.py, and place it into the public domain.
 #   -- Michael Hobbs
 
 
 def start():
-	global demo_
-	demo_ = spawn(demo)
-	return demo_
+    global demo_
+    demo_ = spawn(demo)
+    return demo_
 
 
 def demo():
-	processFlag('trap_exit', True)
-	demo1 = Demo1()
-	demo1.demo1()
+    processFlag('trap_exit', True)
+    demo1 = Demo1()
+    demo1.demo1()
 
 
-class Demo1:
-	def __init__(self):
-		self.stop = False
+class Demo1(object):
+    def __init__(self):
+        self.stop = False
 
-	def normalExit(self, msg):
-		_, from_, _ = msg
-		print 'Demo process received normal exit from %s' % from_
+    def normalExit(self, msg):
+        _, from_, _ = msg
+        print 'Demo process received normal exit from %s' % from_
 
-	def otherExit(self, msg):
-		_, from_, reason = msg
-		print 'Demo process received exit signal %s from %s' % (reason, from_)
+    def otherExit(self, msg):
+        _, from_, reason = msg
+        print 'Demo process received exit signal %s from %s' % (reason, from_)
 
-	def finished(self):
-		print 'Demo finished '
-		self.stop = True
+    def finished(self):
+        print 'Demo finished '
+        self.stop = True
 
-	def other(self, msg):
-		print 'Demo process message %s' % msg
+    def other(self, msg):
+        print 'Demo process message %s' % msg
 
-	def demo1(self):
-		r = Receiver()
-		r.addHandler(('EXIT', Process, 'normal'), self.normalExit, Message)
-		r.addHandler(('EXIT', Process, Any), self.otherExit, Message)
-		r.addHandler('finished_demo', self.finished)
-		r.addHandler(Any, self.other, Message)
-		for _ in r:
-			if self.stop:
-				break
-			# end if
-		return True
+    def demo1(self):
+        r = Receiver()
+        r.addHandler(('EXIT', Process, 'normal'), self.normalExit, Message)
+        r.addHandler(('EXIT', Process, Any), self.otherExit, Message)
+        r.addHandler('finished_demo', self.finished)
+        r.addHandler(Any, self.other, Message)
+        for _ in r:
+            if self.stop:
+                break
+            # end if
+        return True
 
 
 def demonstrate_normal():
-	def func():
-		link(demo_)
-	return spawn(func)
+    def func():
+        link(demo_)
+    return spawn(func)
 
 
 def demonstrate_exit(what):
-	def func():
-		link(demo_)
-		exit(what)
-	return spawn(func)
+    def func():
+        link(demo_)
+        exit(what)
+    return spawn(func)
 
 
 def demonstrate_message(what):
-	def func():
-		demo_.send(what)
-	return spawn(func)
+    def func():
+        demo_.send(what)
+    return spawn(func)
 
 
 def demonstrate_error():
-	def func():
-		link(demo_)
-		1 / 0
-	return spawn(func)
+    def func():
+        link(demo_)
+        1 / 0
+    return spawn(func)

examples/sliding_window.py

+# -*- coding: utf-8 -*-
 # I hereby disclaim all copyright to the contents of this file,
 # sliding_window.py, and place it into the public domain.
 #   -- Michael Hobbs
 receivers.
 
 To send a message to the receiver, send a tuple of the form (self, rcvr, msg) to
-the SlidingWindow process, where 'self' is the sending process, 'rcvr' is the 
+the SlidingWindow process, where 'self' is the sending process, 'rcvr' is the
 receiver process, and 'msg' is the message to send. When the message has been
 delivered to the receiver process, the SlidingWindow will send a tuple of the
 form ('ack', rcvr) to the sending process, where 'rcvr' is the receiver process.
 from candygram import *
 
 
-class SlidingWindow:
-	
-	"""The sliding window class.
+class SlidingWindow(object):
 
-	Standard usage is swProc = SlidingWindow().spawn()
-	The process never terminates naturally. In order to stop it, call
-	exit(swProc, 'kill')
-	"""
+    """The sliding window class.
 
-	def __init__(self):
-		# Contains (currentSize, maxSize) tuples for windows of each known receiver 
-		# process.
-		self.__sizes = {}
-		# Contains [sender] list for sender processes waiting for an acknowledgement
-		# from a receiver process.
-		self.__waiters = {}
-		# Set to True after the process has been spawned.
-		self.__running = False
+    Standard usage is swProc = SlidingWindow().spawn()
+    The process never terminates naturally. In order to stop it, call
+    exit(swProc, 'kill')
+    """
 
-	def spawn(self):
-		assert not self.__running, 'This SlidingWindow has already been spawned'
-		self.__running = True
-		return spawn(self.__run)
+    def __init__(self):
+        # Contains (currentSize, maxSize) tuples for windows of each known receiver
+        # process.
+        self.__sizes = {}
+        # Contains [sender] list for sender processes waiting for an acknowledgement
+        # from a receiver process.
+        self.__waiters = {}
+        # Set to True after the process has been spawned.
+        self.__running = False
 
-	def spawnLink(self):
-		assert not self.__running, 'This SlidingWindow has already been spawned'
-		self.__running = True
-		return spawnLink(self.__run)
+    def spawn(self):
+        assert not self.__running, 'This SlidingWindow has already been spawned'
+        self.__running = True
+        return spawn(self.__run)
 
-	def __run(self):
-		processFlag('trap_exit', True)
-		r = Receiver()
-		r['set_size', Process, int] = self.__setMaxSize, Message
-		r['get_size', Process, Process] = self.__getSize, Message
-		r['EXIT', Process, Any] = self.__exit, Message
-		r['ack', Process] = self.__ack, Message
-		r[Process, Process, Any] = self.__send, Message
-		r[Any]  # ignore spurrious messages
-		for _ in r:
-			pass
-		# end for
+    def spawnLink(self):
+        assert not self.__running, 'This SlidingWindow has already been spawned'
+        self.__running = True
+        return spawnLink(self.__run)
 
-	def __setMaxSize(self, message):
-		_, receiver, maxSize = message
-		# Reset the maxSize value in receiver's size tuple.
-		recvId = id(receiver)
-		size = self.__sizes.get(recvId, (0, 0))[0]
-		self.__sizes[recvId] = (size, maxSize)
-		# We want to know when the receiver exits, so that we can clear its entry
-		# from self.__sizes when it goes away.
-		link(receiver)
+    def __run(self):
+        processFlag('trap_exit', True)
+        r = Receiver()
+        r['set_size', Process, int] = self.__setMaxSize, Message
+        r['get_size', Process, Process] = self.__getSize, Message
+        r['EXIT', Process, Any] = self.__exit, Message
+        r['ack', Process] = self.__ack, Message
+        r[Process, Process, Any] = self.__send, Message
+        r[Any]  # ignore spurrious messages
+        for _ in r:
+            pass
+        # end for
 
-	def __getSize(self, message):
-		_, receiver, proc = message
-		# Retrieve the maxSize value from receiver's size tuple.
-		recvId = id(receiver)
-		size = self.__sizes.get(recvId, (0, 0))[0]
-		proc | (self_(), 'size', size)
+    def __setMaxSize(self, message):
+        _, receiver, maxSize = message
+        # Reset the maxSize value in receiver's size tuple.
+        recvId = id(receiver)
+        size = self.__sizes.get(recvId, (0, 0))[0]
+        self.__sizes[recvId] = (size, maxSize)
+        # We want to know when the receiver exits, so that we can clear its entry
+        # from self.__sizes when it goes away.
+        link(receiver)
 
-	def __exit(self, message):
-		_, receiver, _ = message
-		# A process has terminated, delete all references to it from our dicts.
-		recvId = id(receiver)
-		assert recvId in self.__sizes
-		del self.__sizes[recvId]
-		if recvId in self.__waiters:
-			del self.__waiters[recvId]
-		# end if
+    def __getSize(self, message):
+        _, receiver, proc = message
+        # Retrieve the maxSize value from receiver's size tuple.
+        recvId = id(receiver)
+        size = self.__sizes.get(recvId, (0, 0))[0]
+        proc | (self_(), 'size', size)
 
-	def __ack(self, message):
-		receiver = message[1]
-		# Lookup current window size of receiver.
-		recvId = id(receiver)
-		assert recvId in self.__sizes
-		size, maxSize = self.__sizes[recvId]
-		# If there are any senders are waiting for acknowledgement from this 
-		# receiver, then the receiver's window should be full. (Otherwise the
-		# acknowledgement would have already been sent to the sender.)
-		if recvId in self.__waiters:
-			# Sanity check to make sure that the window is full:
-			assert size == maxSize
-			waiters = self.__waiters[recvId]
-			sender, message = waiters.pop(0)
-			if not waiters:
-				# clean up empty dictionary entries
-				del self.__waiters[recvId]
-			receiver | message
-			sender | ('ack', receiver)
-		else:
-			# Sanity check to make sure that the process isn't acknowledging when its
-			# window is empty:
-			assert size > 0
-			self.__sizes[recvId] = (size - 1, maxSize)
-		# end if
+    def __exit(self, message):
+        _, receiver, _ = message
+        # A process has terminated, delete all references to it from our dicts.
+        recvId = id(receiver)
+        assert recvId in self.__sizes
+        del self.__sizes[recvId]
+        if recvId in self.__waiters:
+            del self.__waiters[recvId]
+        # end if
 
-	def __send(self, message):
-		sender, dest, message = message
-		destId = id(dest)
-		# Define a new window with a default maxSize of 1 if we haven't already
-		# encoutered this receiver process.
-		if destId not in self.__sizes:
-			self.__setMaxSize((None, dest, 1))
-		size, maxSize = self.__sizes[destId]
-		# If the receiver's window is full, add current sender to the queue of
-		# senders that are waiting for an acknowledgement from the receiver. If the
-		# receiver's window is not full, send an acknowledgement back to the sender
-		# right away.
-		if size == maxSize:
-			self.__waiters.setdefault(destId, []).append((sender, message))
-		else:
-			# Sanity check to make sure size hasn't somehow exceeded maxSize:
-			assert size < maxSize
-			dest | message
-			sender | ('ack', dest)
-			self.__sizes[destId] = (size + 1, maxSize)
-		# end if
+    def __ack(self, message):
+        receiver = message[1]
+        # Lookup current window size of receiver.
+        recvId = id(receiver)
+        assert recvId in self.__sizes
+        size, maxSize = self.__sizes[recvId]
+        # If there are any senders are waiting for acknowledgement from this
+        # receiver, then the receiver's window should be full. (Otherwise the
+        # acknowledgement would have already been sent to the sender.)
+        if recvId in self.__waiters:
+            # Sanity check to make sure that the window is full:
+            assert size == maxSize
+            waiters = self.__waiters[recvId]
+            sender, message = waiters.pop(0)
+            if not waiters:
+                # clean up empty dictionary entries
+                del self.__waiters[recvId]
+            receiver | message
+            sender | ('ack', receiver)
+        else:
+            # Sanity check to make sure that the process isn't acknowledging when its
+            # window is empty:
+            assert size > 0
+            self.__sizes[recvId] = (size - 1, maxSize)
+        # end if
+
+    def __send(self, message):
+        sender, dest, message = message
+        destId = id(dest)
+        # Define a new window with a default maxSize of 1 if we haven't already
+        # encoutered this receiver process.
+        if destId not in self.__sizes:
+            self.__setMaxSize((None, dest, 1))
+        size, maxSize = self.__sizes[destId]
+        # If the receiver's window is full, add current sender to the queue of
+        # senders that are waiting for an acknowledgement from the receiver. If the
+        # receiver's window is not full, send an acknowledgement back to the sender
+        # right away.
+        if size == maxSize:
+            self.__waiters.setdefault(destId, []).append((sender, message))
+        else:
+            # Sanity check to make sure size hasn't somehow exceeded maxSize:
+            assert size < maxSize
+            dest | message
+            sender | ('ack', dest)
+            self.__sizes[destId] = (size + 1, maxSize)
+        # end if

examples/wxprocess.py

+# -*- coding: utf-8 -*-
 # I hereby disclaim all copyright to the contents of this file,
 # wxprocess.py, and place it into the public domain.
 #   -- Michael Hobbs
 
 class wxProcess(cg.Process):
 
-	"""A wxPython compatible Process class"""
+    """A wxPython compatible Process class"""
 
-	def __init__(self):
-		# Don't bind a custom notification event to wx.App at this point, since
-		# a wx.App shouldn't be instantiated yet. We bind to the wx.App, instead,
-		# when the first time send() is called.
-		cg.Process.__init__(self)
-		self.__app = None
-		self.__notifyEventType = None
-		self.receiver = cg.Receiver()
+    def __init__(self):
+        # Don't bind a custom notification event to wx.App at this point, since
+        # a wx.App shouldn't be instantiated yet. We bind to the wx.App, instead,
+        # when the first time send() is called.
+        cg.Process.__init__(self)
+        self.__app = None
+        self.__notifyEventType = None
+        self.receiver = cg.Receiver()
 
-	def send(self, message):
-		"""Send message to the process and then send notification event"""
-		self.__checkAppBound()
-		cg.Process.send(self, message)
-		notifyEvent = wx.PyEvent()
-		notifyEvent.SetEventType(self.__notifyEventType)
-		wx.PostEvent(self.__app, notifyEvent)
+    def send(self, message):
+        """Send message to the process and then send notification event"""
+        self.__checkAppBound()
+        cg.Process.send(self, message)
+        notifyEvent = wx.PyEvent()
+        notifyEvent.SetEventType(self.__notifyEventType)
+        wx.PostEvent(self.__app, notifyEvent)
 
-	def __checkAppBound(self):
-		"""Bind custom notification event to wx.App"""
-		if self.__app is not None:
-			return
-		# Save a copy of wx.GetApp() locally so that we don't have to refetch it
-		# every time send() is called.
-		self.__app = wx.GetApp()
-		self.__notifyEventType = wx.NewEventType()
-		notifyEventBinder = wx.PyEventBinder(self.__notifyEventType, 0)
-		self.__app.Bind(notifyEventBinder, self.__receive)
+    def __checkAppBound(self):
+        """Bind custom notification event to wx.App"""
+        if self.__app is not None:
+            return
+        # Save a copy of wx.GetApp() locally so that we don't have to refetch it
+        # every time send() is called.
+        self.__app = wx.GetApp()
+        self.__notifyEventType = wx.NewEventType()
+        notifyEventBinder = wx.PyEventBinder(self.__notifyEventType, 0)
+        self.__app.Bind(notifyEventBinder, self.__receive)
 
-	def __receive(self, event):
-		"""Called in response to a notification event"""
-		# Since this method is only be invoked when a new message is present, we can
-		# set a timeout of 0.
-		self.receiver.receive(0)
+    def __receive(self, event):
+        """Called in response to a notification event"""
+        # Since this method is only be invoked when a new message is present, we can
+        # set a timeout of 0.
+        self.receiver.receive(0)
 
 
 def sampleSpawn():
-	"""Start GUI event loop in separate process"""
-	# Unique value used to acknowledge that the wx.App has been created:
-	ack = object()
-	# Unique value used to signal a receive() timeout:
-	timeout = object()
-	# Spawn a new wxProcess, calling mainLoop():
-	proc = cg.spawn(mainLoop, cg.self(), ack, _processClass=wxProcess)
-	# We wait for acknowledgement from the spawned process before proceeding,
-	# since we should make sure that the wx.App has been instantiated before
-	# allowing anyone to send messages to the process.
-	r = cg.Receiver()
-	r.addHandler(ack)
-	# Wait at most 30 seconds.
-	result = r.receive(30000, lambda: timeout)
-	assert result is not timeout
-	return proc
+    """Start GUI event loop in separate process"""
+    # Unique value used to acknowledge that the wx.App has been created:
+    ack = object()
+    # Unique value used to signal a receive() timeout:
+    timeout = object()
+    # Spawn a new wxProcess, calling mainLoop():
+    proc = cg.spawn(mainLoop, cg.self(), ack, _processClass=wxProcess)
+    # We wait for acknowledgement from the spawned process before proceeding,
+    # since we should make sure that the wx.App has been instantiated before
+    # allowing anyone to send messages to the process.
+    r = cg.Receiver()
+    r.addHandler(ack)
+    # Wait at most 30 seconds.
+    result = r.receive(30000, lambda: timeout)
+    assert result is not timeout
+    return proc
 
 
 def mainLoop(proc, ack):
-	"""Create a wx.PySimpleApp and run its MainLoop()"""
-	app = wx.PySimpleApp()
-	proc.send(ack)
-	# We can define our Candygram handler functions here:
-	r = cg.self().receiver
-	# r.addHandler(...)
-	# r.addHandler(...)
-	# ... and so on ...
-	app.MainLoop()
+    """Create a wx.PySimpleApp and run its MainLoop()"""
+    app = wx.PySimpleApp()
+    proc.send(ack)
+    # We can define our Candygram handler functions here:
+    r = cg.self().receiver
+    # r.addHandler(...)
+    # r.addHandler(...)
+    # ... and so on ...
+    app.MainLoop()
+# -*- coding: utf-8 -*-
 # I hereby disclaim all copyright to the contents of this file,
 # setup.py, and place it into the public domain.
 #   -- Michael Hobbs
 
 
 setup(name = 'Candygram',
-		version = '1.0',
+		version = '1.1',
 		license = 'GNU Lesser General Public License',
 		url = 'http://candygram.sourceforge.net',
 		author = 'Michael Hobbs',
 
 
 from candygram.main import spawn, spawnLink, self, self_, exit, link, unlink, \
-		processFlag, processes, isProcessAlive, send, ExitError
+        processFlag, processes, isProcessAlive, send, ExitError
 from candygram.process import Process
 from candygram.receiver import Receiver, Message
 from candygram.pattern import Any, AnyRemaining
 
 
 __all__ = ['spawn', 'spawnLink', 'self', 'self_', 'exit', 'link', 'unlink',
-		'processFlag', 'processes', 'isProcessAlive', 'send', 'ExitError',
-		'Process', 'Receiver', 'Message', 'Any']
+        'processFlag', 'processes', 'isProcessAlive', 'send', 'ExitError',
+        'Process', 'Receiver', 'Message', 'Any']
+# -*- coding: utf-8 -*-
 # __init__.py
 #
 # Copyright (c) 2004 Michael Hobbs
 #
+# New classes patch by Antoine Boegli, 2010.
+#
 # This file is part of Candygram.
 #
 # Candygram is free software; you can redistribute it and/or modify
+# -*- coding: utf-8 -*-
 # condition.py
 #
 # Copyright (c) 2004 Michael Hobbs
 #
+# New classes patch by Antoine Boegli, 2010.
+#
 # This file is part of Candygram.
 #
 # Candygram is free software; you can redistribute it and/or modify
 from candygram.threadimpl import allocateLock
 
 
-class Condition:
+class Condition(object):
 
-	"""modified Condition class"""
+    """modified Condition class"""
 
-	def __init__(self):
-		self.__lock = allocateLock()
-		self.acquire = self.__lock.acquire
-		self.release = self.__lock.release
-		self.locked = self.__lock.locked
-		self.__waiter = None
+    def __init__(self):
+        self.__lock = allocateLock()
+        self.acquire = self.__lock.acquire
+        self.release = self.__lock.release
+        self.locked = self.__lock.locked
+        self.__waiter = None
 
-	def wait(self, timeout=None):
-		"""wait for notify()"""
-		assert self.locked()
-		waiter = allocateLock()
-		waiter.acquire()
-		self.__waiter = waiter
-		self.release()
-		try:
-			return _acquire(waiter, timeout)
-		finally:
-			self.acquire()
-		# end try
+    def wait(self, timeout=None):
+        """wait for notify()"""
+        assert self.locked()
+        waiter = allocateLock()
+        waiter.acquire()
+        self.__waiter = waiter
+        self.release()
+        try:
+            return _acquire(waiter, timeout)
+        finally:
+            self.acquire()
+        # end try
 
-	def notify(self):
-		"""wake up wait()ers"""
-		assert self.locked()
-		if self.__waiter is not None:
-			self.__waiter.release()
-			self.__waiter = None
-		# end if
+    def notify(self):
+        """wake up wait()ers"""
+        assert self.locked()
+        if self.__waiter is not None:
+            self.__waiter.release()
+            self.__waiter = None
+        # end if
 
 
 def _acquire(lock, timeout):
-	"""try to acquire a lock, with a timeout"""
-	if timeout is None:
-		lock.acquire()
-		return True
-	timeout = time.time() + timeout
-	delay = 0.0005  # 500 us -> initial delay of 1 ms
-	while True:
-		if lock.acquire(0):
-			return True
-		remaining = timeout - time.time()
-		if remaining <= 0:
-			break
-		delay = min(delay * 2, remaining, .05)
-		time.sleep(delay)
-	return False
+    """try to acquire a lock, with a timeout"""
+    if timeout is None:
+        lock.acquire()
+        return True
+    timeout = time.time() + timeout
+    delay = 0.0005  # 500 us -> initial delay of 1 ms
+    while True:
+        if lock.acquire(0):
+            return True
+        remaining = timeout - time.time()
+        if remaining <= 0:
+            break
+        delay = min(delay * 2, remaining, .05)
+        time.sleep(delay)
+    return False
 
 
 def spawn(func, *args, **kwargs):
-	"""spawn new process"""
-	return _doSpawn(func, args, kwargs, None)
+    """spawn new process"""
+    return _doSpawn(func, args, kwargs, None)
 
 
 def spawnLink(func, *args, **kwargs):
-	"""spawn and link to a new process atomically"""
-	return _doSpawn(func, args, kwargs, self())
+    """spawn and link to a new process atomically"""
+    return _doSpawn(func, args, kwargs, self())
 
 
 def _doSpawn(func, args, kwargs, initialLink):
-	"""performs initiation of new process thread"""
-	_checkSignal()
-	if not callable(func):
-		raise ExitError('badarg')
-	class_ = Process
-	if '_processClass' in kwargs:
-		class_ = kwargs['_processClass']
-		del kwargs['_processClass']
-	proc = class_()
-	proc._startThread(func, args, kwargs, initialLink)
-	return proc
+    """performs initiation of new process thread"""
+    _checkSignal()
+    if not callable(func):
+        raise ExitError('badarg')
+    class_ = Process
+    if '_processClass' in kwargs:
+        class_ = kwargs['_processClass']
+        del kwargs['_processClass']
+    proc = class_()
+    proc._startThread(func, args, kwargs, initialLink)
+    return proc
 
 
 def self(noCheck=False):
-	"""return current process"""
-	# _checkSignal() needs to invoke self(). In order to avoid infinite recursion,
-	# don't call _checkSignal() if noCheck is set.
-	if not noCheck:
-		_checkSignal()
-	getProcessMapLock().acquire()
-	try:
-		currentThread = getCurrentThread()
-		assert currentThread in getProcessMap(), \
-				'Only the main thread or threads created by spawn*() may invoke self()'
-		result = getProcessMap()[currentThread]
-	finally:
-		getProcessMapLock().release()
-	return result
+    """return current process"""
+    # _checkSignal() needs to invoke self(). In order to avoid infinite recursion,
+    # don't call _checkSignal() if noCheck is set.
+    if not noCheck:
+        _checkSignal()
+    getProcessMapLock().acquire()
+    try:
+        currentThread = getCurrentThread()
+        assert currentThread in getProcessMap(), \
+                'Only the main thread or threads created by spawn*() may invoke self()'
+        result = getProcessMap()[currentThread]
+    finally:
+        getProcessMapLock().release()
+    return result
 
 # Alternate name so that the self() function can be used in class methods where
 # 'self' is already defined:
 
 
 def exit(*args):
-	"""kill a process"""
-	_checkSignal()
-	numArgs = len(args)
-	if numArgs == 0 or numArgs > 2:
-		raise ExitError('badarg')
-	if numArgs == 1:
-		raise ExitError(args[0])
-	elif not isinstance(args[0], Process):
-		raise ExitError('badarg')
-	args[0]._signal(ExitError(args[1]))
-	return True
+    """kill a process"""
+    _checkSignal()
+    numArgs = len(args)
+    if numArgs == 0 or numArgs > 2:
+        raise ExitError('badarg')
+    if numArgs == 1:
+        raise ExitError(args[0])
+    elif not isinstance(args[0], Process):
+        raise ExitError('badarg')
+    args[0]._signal(ExitError(args[1]))
+    return True
 
 
 def link(proc):
-	"""link to a process"""
-	_checkSignal()
-	if not isinstance(proc, Process):
-		raise ExitError('badarg')
-	selfProc = self()
-	selfProc._addLink(proc)
-	# The above call may raise a 'noproc' signal
-	_checkSignal()
-	proc._addLink(selfProc)
-	return True
+    """link to a process"""
+    _checkSignal()
+    if not isinstance(proc, Process):
+        raise ExitError('badarg')
+    selfProc = self()
+    selfProc._addLink(proc)
+    # The above call may raise a 'noproc' signal
+    _checkSignal()
+    proc._addLink(selfProc)
+    return True
 
 
 def unlink(proc):
-	"""remove link to a process"""
-	_checkSignal()
-	if not isinstance(proc, Process):
-		raise ExitError('badarg')
-	selfProc = self()
-	proc._removeLink(selfProc)
-	selfProc._removeLink(proc)
-	return True
+    """remove link to a process"""
+    _checkSignal()
+    if not isinstance(proc, Process):
+        raise ExitError('badarg')
+    selfProc = self()
+    proc._removeLink(selfProc)
+    selfProc._removeLink(proc)
+    return True
 
 
 def processFlag(flag, value):
-	"""set a process flag"""
-	return self()._processFlag(flag, value)
+    """set a process flag"""
+    return self()._processFlag(flag, value)
 
 
 def processes():
-	"""list all active processes"""
-	_checkSignal()
-	getProcessMapLock().acquire()
-	try:
-		return getProcessMap().values()
-	finally:
-		getProcessMapLock().release()
-	# end try
+    """list all active processes"""
+    _checkSignal()
+    getProcessMapLock().acquire()
+    try:
+        return getProcessMap().values()
+    finally:
+        getProcessMapLock().release()
+    # end try
 
 
 def isProcessAlive(proc):
-	"""return True if process is active"""
-	if not isinstance(proc, Process):
-		raise ExitError('badarg')
-	return proc.isAlive()
+    """return True if process is active"""
+    if not isinstance(proc, Process):
+        raise ExitError('badarg')
+    return proc.isAlive()
 
 
 def send(proc, msg):
-	"""send a message to process"""
-	if not isinstance(proc, Process):
-		raise ExitError('badarg')
-	return proc.send(msg)
+    """send a message to process"""
+    if not isinstance(proc, Process):
+        raise ExitError('badarg')
+    return proc.send(msg)
 
 
 def _checkSignal():
-	"""check if a signal has been sent to current process"""
-	self(True)._checkSignal()
+    """check if a signal has been sent to current process"""
+    self(True)._checkSignal()
 
 
 class ExitError(Exception):
 
-	"""raised by EXIT signals"""
+    """raised by EXIT signals"""
 
-	def __init__(self, reason, proc=None):
-		Exception.__init__(self, reason)
-		self.reason = reason
-		if proc is None:
-			self.proc = self_()
-		else:
-			self.proc = proc
-		# end if
+    def __init__(self, reason, proc=None):
+        Exception.__init__(self, reason)
+        self.reason = reason
+        if proc is None:
+            self.proc = self_()
+        else:
+            self.proc = proc
+        # end if
 
 
 # We can't import these at the top, since the process module imports this one
 
 
 def genFilter(pattern):
-	"""generate a pattern filter"""
-	if isinstance(pattern, tuple) or isinstance(pattern, list):
-		result = genSeqFilter(pattern)
-	elif isinstance(pattern, dict):
-		result = genDictFilter(pattern)
-	elif isinstance(pattern, type) or type(pattern) is types.ClassType:
-		result = genTypeFilter(pattern)
-	elif callable(pattern):
-		result = genFuncFilter(pattern)
-	elif pattern is Any:
-		result = genAnyFilter()
-	elif pattern is AnyRemaining:
-		warnings.warn(
-				'The candygram.AnyRemaining constant is deprecated. ' \
-				'Please use a standard list pattern instead.',
-				DeprecationWarning,
-				5)  # Usually called from addHandler(genFilter(genSeqFilter(...)))
-		result = genAnyFilter()
-	else:
-		result = genValueFilter(pattern)
-	return result
+    """generate a pattern filter"""
+    if isinstance(pattern, tuple) or isinstance(pattern, list):
+        result = genSeqFilter(pattern)
+    elif isinstance(pattern, dict):
+        result = genDictFilter(pattern)
+    elif isinstance(pattern, type) or type(pattern) is types.ClassType:
+        result = genTypeFilter(pattern)
+    elif callable(pattern):
+        result = genFuncFilter(pattern)
+    elif pattern is Any:
+        result = genAnyFilter()
+    elif pattern is AnyRemaining:
+        warnings.warn(
+                'The candygram.AnyRemaining constant is deprecated. ' \
+                'Please use a standard list pattern instead.',
+                DeprecationWarning,
+                5)  # Usually called from addHandler(genFilter(genSeqFilter(...)))
+        result = genAnyFilter()
+    else:
+        result = genValueFilter(pattern)
+    return result
 
 
 def genAnyFilter():
-	"""gen filter for Any"""
-	return lambda x: True
+    """gen filter for Any"""
+    return lambda x: True
 
 
 def genValueFilter(value):
-	"""gen filter for a specific value"""
-	return lambda x: x == value
+    """gen filter for a specific value"""
+    return lambda x: x == value
 
 
 def genFuncFilter(func):
-	"""gen filter for a function"""
-	return func
+    """gen filter for a function"""
+    return func
 
 
 def genTypeFilter(t):
-	"""gen filter for a type check"""
-	return lambda x: isinstance(x, t)
+    """gen filter for a type check"""
+    return lambda x: isinstance(x, t)
 
 
 def genSeqFilter(seq):
-	"""gen filter for a sequence pattern"""
-	# Define these values as constants outside of the filt() function so that
-	# the filter will not have to re-calculate the values every time it's called.
-	lastFilter = None
-	if isinstance(seq, list) and seq:
-		lastFilter = genFilter(seq[-1])
-		seq = seq[:-1]
-	seqType = type(seq)