473,809 Members | 2,701 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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(handl er):
print " enter drive"
yield "current speed"

while 1:
try:
handler.registe r(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(obj ect):

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

def addTask(self, task):
self.tasks.appe nd(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.remo ve(t)
else: # normal method/function
t()
from sys import settrace

class SignalingTaskHa ndler(TaskHandl er):

def __init__(self):
super(Signaling TaskHandler, self).__init__( )

self.function2s ignal = {}
self.activeSign als = ()
self.newSignals = []
self.loopTask = self.__loop()

def register(self, aFunction, signals):
self.function2s ignal[id(aFunction.fu nc_code)] = signals

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

def loop(self):
self.loopTask.n ext()

def __loop(self):
while 1:
settrace(self._ _intercept)
tmp = len(self.newSig nals)

try:
super(Signaling TaskHandler, 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.newSig nals):
self.__step()

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

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

if self.activeSign als:
signals = self.function2s ignal[key]
# check if there is one signal to raise
for s in self.activeSign als:
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.function2s ignal:
return _i

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

class NoPower(Excepti on):
pass

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

while 1:
try:
handler.registe r(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 = SignalingTaskHa ndler()
tmp = driveTask(handl er)
handler.addTask (tmp)

# main loop

mainTaskHandler = TaskHandler()

# well, there could be a lot more
mainTaskHandler .addTask(miscTa sk)
mainTaskHandler .addTask(handle r.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 1602
Dominic wrote:
...
class TaskHandler(obj ect):
def __init__(self):
self.tasks = []
def addTask(self, task):
self.tasks.appe nd(task)
def removeTask(self , task):
del self.tasks[task]
...


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

Or, perhaps:
class TaskHandler(obj ect):
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***********@A cm.Org
Jul 18 '05 #2

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

Similar topics

9
2691
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 open, even though it's at least a year old and Guido doesn't seem very hot on the idea). I'm not too sure of its ideas on raising exceptions in generators from outside (although it looks like it might be convenient in some cases), but being able...
10
1980
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 generator functions compatible with a standard thread interface, I attempted to write a decorator which converts a standard
10
1554
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 refrained from using them often. But are they 'slow' in general? I guess it also depends on how, when and where you use them. What I am looking for is a sort of guideline that explains where exceptions are approriate and where they are not. The...
59
4458
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 presented that says "Use conventional error-handling techniques rather than exception handling for straightforward local error processing in which a program is easily able to deal with its own errors." By "conventional error-handling," I believe...
15
426
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 have been asked on clc before so it is probably OK. I am a newbie to C++. BS 3rd edition states: % The throw transfers control to a handler for exceptions .... %
4
1856
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 it has now, after 15k lines of code resulted in a royal mess! It's my hope to ask some specific questions with scenario examples and that some of you might offer a little guidance or general suggestions. 1) string...
4
1435
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). Personally, I don't like code generators. I inherited two web applications that use LLBLGen, and they are just impossible to debug. It generates so many classes and so much code that isn't actually used. In my case, I'm maintaining web app with...
9
5174
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 __init__(self, *items): self.stack = list(items) def push(self, item): self.stack.append(item)
14
4361
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 ignored when called. I can see the attribute using dir(self.__class__) on an instance, but when called, python enters __getattr__. If I correct the bug, the attribute calls work as expected and do not call __getattr__. I can't seem to make a simple...
0
9721
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10639
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10383
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9200
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6881
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5550
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4332
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3861
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3015
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.