473,322 Members | 1,347 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,322 software developers and data experts.

raise exceptions in generators/functions from other tasks/functions

Just in case someone is interested.
I came up with this solution since my previous
posting.
Maybe you've got some other ideas or critcism.
I'll listen ;-)

Ciao,
Dominic

P.S. Python is really powerful!

Use-Case:

def driveTask(handler):
print " enter drive"
yield "current speed"

while 1:
try:
handler.register(driveTask, (NoPower, WallHit))
while 1:
print " adjust engine"
yield "current speed"
print " steer"

except WallHit:
print "hit the wall :-("
except NoPower:
print "need some fresh batteries :-)"
================================================== ==================

Full-Source code:

from types import GeneratorType

class TaskHandler(object):

def __init__(self):
self.tasks = []

def addTask(self, task):
self.tasks.append(task)

def removeTask(self, task):
del self.tasks[task]

def loop(self):
for t in self.tasks:
# generator task
if type(t) == GeneratorType:
if not t.next():
# generator is done, remove it
self.tasks.remove(t)
else: # normal method/function
t()
from sys import settrace

class SignalingTaskHandler(TaskHandler):

def __init__(self):
super(SignalingTaskHandler, self).__init__()

self.function2signal = {}
self.activeSignals = ()
self.newSignals = []
self.loopTask = self.__loop()

def register(self, aFunction, signals):
self.function2signal[id(aFunction.func_code)] = signals

def signal(self, aSignal):
if not aSignal in self.newSignals:
self.newSignals.append(aSignal)

def loop(self):
self.loopTask.next()

def __loop(self):
while 1:
settrace(self.__intercept)
tmp = len(self.newSignals)

try:
super(SignalingTaskHandler, self).loop()
finally:
settrace(None)

# if we've reached "steady state", we make a step
# I think Esterel-language has similar signaling semantics
if tmp == len(self.newSignals):
self.__step()

yield True
def __step(self):
# switch to new signal set, discard old ones
self.activeSignals = tuple(self.newSignals)
self.newSignals = []

def __intercept(self, frame, event, arg):
def _i(frame, event, arg):
# we could return _i to trace inside function
# and not only calls to it

if self.activeSignals:
signals = self.function2signal[key]
# check if there is one signal to raise
for s in self.activeSignals:
if s in signals:
raise s

# every function gets it's own tracer, otherwise
# exceptions cannot be catched :-( Why?
key = id(frame.f_code)
if key in self.function2signal:
return _i

return None
# A Use Case :
class WallHit(Exception):
pass

class NoPower(Exception):
pass

def driveTask(handler):
print " enter drive"
yield "current speed"

while 1:
try:
handler.register(driveTask, (NoPower, WallHit))
while 1:
print " adjust engine"
yield "current speed"
print " steer"

except WallHit:
print "hit the wall :-("
except NoPower:
print "need some fresh batteries :-)"

counter = 0

def miscTask():
global counter

if counter == 4:
handler.signal(WallHit)
if counter == 5:
handler.signal(NoPower)

counter += 1

# "special" tasks with signaling
handler = SignalingTaskHandler()
tmp = driveTask(handler)
handler.addTask(tmp)

# main loop

mainTaskHandler = TaskHandler()

# well, there could be a lot more
mainTaskHandler.addTask(miscTask)
mainTaskHandler.addTask(handler.loop)
for _ in range(10):
mainTaskHandler.loop()
# enter drive
# adjust engine
# steer
# adjust engine
# steer
# adjust engine
# steer
# adjust engine
# hit the wall :-(
# adjust engine
# need some fresh batteries :-)
# adjust engine
# steer
# adjust engine
# steer
# adjust engine
# steer
# adjust engine
Jul 18 '05 #1
1 1561
Dominic wrote:
...
class TaskHandler(object):
def __init__(self):
self.tasks = []
def addTask(self, task):
self.tasks.append(task)
def removeTask(self, task):
del self.tasks[task]
...


I think you mean:
def removeTask(self, task):
self.tasks.remove(task)

Or, perhaps:
class TaskHandler(object):
def __init__(self):
self.tasks = {}
def addTask(self, task):
self.tasks[task] = task
def removeTask(self, task):
del self.tasks[task]

--
-Scott David Daniels
Sc***********@Acm.Org
Jul 18 '05 #2

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

Similar topics

9
by: Francis Avila | last post by:
A little annoyed one day that I couldn't use the statefulness of generators as "resumable functions", I came across Hettinger's PEP 288 (http://www.python.org/peps/pep-0288.html, still listed as...
10
by: Simon Wittber | last post by:
I use a coroutine/generator framework for simulating concurrent processes. To do this, I write all my functions using the general form: while True: do stuff yield None To make these...
10
by: Jakob Bieling | last post by:
Hi, somehow the prejudice of exceptions being rather slow (compared to, ie. returning an error value and checking that) keeps sticking around .. at least around me. I guess this is also why I...
59
by: kk_oop | last post by:
Hi. I wanted to use exceptions to handle error conditions in my code. I think doing that is useful, as it helps to separate "go" paths from error paths. However, a coding guideline has been...
15
by: Bernard | last post by:
Hi All, I am not sure if I should be asking this question on clc or clc++. Let me try on both. I hope that this is not too trivial for the brilliant minds over here. I know that OOP questions...
4
by: Steve | last post by:
I have read a couple articles online, read my Jesse Liberty book but I am still confused as to just what the best practices are for using exceptions. I keep changing how I'm working with them and...
4
by: VMI | last post by:
In the next few weeks, we'll be discussing what standards will be used for our web development, and one of the suggestions was to use a code generator (in our case, the first version of LLBLGen)....
9
by: ssecorp | last post by:
Is this correct use of exceptions? to raise an indexerror and add my own string insetad of just letting it raise a IndexError by itself and "blaming" it on list.pop? class Stack(object): def...
14
by: Rafe | last post by:
Hi, I've encountered a problem which is making debugging less obvious than it should be. The @property decorator doesn't always raise exceptions. It seems like it is bound to the class but...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

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.