Tuesday, September 23, 2008
Special Price on E-book Version of Path Into Darkness
For the next week (until 4pm, Tuesday September 30, 2008), the price for the e-book download version of Stephen Coursen's Path Into Darkness is reduced to $2.95.
Any blogger interested in doing a review of the book, can contact me in the comments section and I'll get them an e-book for review purposes.
Stackless Event Loops
This is a follow-on article to Stackless Python Meets Twisted Matrix. This time how to use function decorators to turn a ordinary looking function in a looping event dispatcher. Useful for the Observer design pattern.
Through the syntactical power of decorators, one can can convert any function into a continuously run event loop. This utilizes Stackless Python, which has been discussed in earlier articles on not only this web site, but many many others as well.
The premise behind this event loop is this: a tasklet runs and dispatches incoming "events" to a handler function. To the outside caller, it appears to be a regular function call, but the mechanisms provided by the decorator allow the execution of the "event handler" to be run in a seperate tasklet. If desired, this premise can be extended further to allow for the event loop to run in its own thread.
First, let's look at the class that does all the heavy lifting.
class ChannelProcessor:This code makes use of the decorators described in an earlier article, available here. As you will notice, the core of the event loop is contained in the process function, which runs in it's own tasklet (due to being decorated by the deferred_tasklet decorator). It doesn't matter if you aren't using Twisted for this code to work, although you will need Twisted installed for it to run (unless you change the mechanices of deferred_tasklet).
def __init__( self, action ):
self.channel = stackless.channel( )
self.action = action
self.running = True
self.process( )
def stop( self ):
self.running = False
self.channel.send( 1 )
@blocking_tasklet
def __call__( self, *args, **kwargs ):
c = stackless.channel( )
self.channel.send( (c,args,kwargs) )
rv = c.receive( )
if isinstance( rv, failure.Failure ):
raise rv.value
return rv
@deferred_tasklet
def process( self ):
while self.running:
vals = self.channel.receive( )
if len( vals ) == 3:
c,args,kwargs = vals
d = defer.Deferred( )
d.addBoth( c.send )
_wrapper( d, self.action, *args, **kwargs )
else:
self.running = False
process simply loops until told otherwise (via the stop method), receiving data from it's channel. If the data is a tuple of 3 items, it calls the original function (stored in the action member). Return value from the event handler is sent on a channel, which we received as the 1st element of the tuple.
An outside caller enters into this mechanism via the __call__ method. This method creates a new channel, and then passes that channel, and the parameters it was called with along the object's channel. It then waits for data to be sent back to it. After a quick look at the data returned, it either returns the data through the traditional means or raises an exception (if it received an exception).
Now, for the decorator:
@decorator
def channel_processor( f, *args, **kwargs ):
func_obj = None
if type( f ) == types.MethodType:
target = f.im_self
target_name = f.func_name + '_cp'
if not hasattr( target, target_name ):
func_obj = ChannelProcessor( f )
setattr( target, target_name, func_obj )
else:
func_obj = getattr( target, target_name )
elif not hasattr( f, "_cp" ):
setattr( f, '_cp', ChannelProcessor( f ) )
func_obj = f._cp
else:
func_obj = f._cp
return func_obj( *args, **kwargs )
Here, we create a ChannelProcessor object and stuff it into the calling function's member list (as a member named _cp). If it already exists, great. In any case, we then call the object, which will lead us into the __call__ method shown above.
A special case is made if we are an object's method, instead of a regular function. This does not happen in the regular use-case of a decorator (when using the @decorator_name syntax). It only happens when we do something like:
class A:You use this method if you need to have each object having it's own tasklet that handles events. Using the standard decorator syntax results in each function having it's own event handling tasklet.
def __init__( self ):
self.func = channel_processor( func )
def func( self, *args ):
print "Here i am with arg list:", args
I tend to use the per-function methodology, but as usual, your mileage may vary.
Labels:
programming,
python,
stackless,
twisted integration
Monday, September 22, 2008
Horses for courses....
Many years ago, when I was still in high school, my parents bought a chunk of undeveloped land in Montana. A few years ago, they retired, bought another, smaller chunk of land in Montana. They moved out west and started up a small ranch.
My daughter spends every summer out there (yay! mini vacation for me!) and has become quite adept at riding and other ranch activities. During her trip this year, she fell off one of the mares and cut her arm up pretty good on some barbed wire fencing. She's quite alright now, and in fact brags about how tough she is when showing off the scar.
Fast forward to yesterday. My mother called and told me that my father fell off of one of the horses (a stallion aptly named Scar). He cut his head open, had to get some stitches and staples. Additionally, he had a level 2 concussion which is causing him the usual side effects of concussions (forgetfulness, nausea, problems sleeping).
So, I decided to give a plug the website for their ranch business, Peak Performance Quarter Horses. I'm involved in the hosting of the site, but had nothing to do with the design.
Anyways, godspeed on my father's recovery.
My daughter spends every summer out there (yay! mini vacation for me!) and has become quite adept at riding and other ranch activities. During her trip this year, she fell off one of the mares and cut her arm up pretty good on some barbed wire fencing. She's quite alright now, and in fact brags about how tough she is when showing off the scar.
Fast forward to yesterday. My mother called and told me that my father fell off of one of the horses (a stallion aptly named Scar). He cut his head open, had to get some stitches and staples. Additionally, he had a level 2 concussion which is causing him the usual side effects of concussions (forgetfulness, nausea, problems sleeping).
So, I decided to give a plug the website for their ranch business, Peak Performance Quarter Horses. I'm involved in the hosting of the site, but had nothing to do with the design.
Anyways, godspeed on my father's recovery.
Sunday, September 21, 2008
Stuff on my bookshelf
I'm picking 5 things off my living room bookshelf (ok, so they're already picked off the shelf ... I did do some footwork before I started to type this). Let's give them a quick review, shall we?
1. Diary of a Wimpy Kid
: This isn't my book. Honest. My daughter loves it. She talks about it constantly, in that way that only ten years can. At her school's book fair last week, she bought the Diary of a Wimpy Kid Do-It-Yourself Book
. She hasn't done anything with it, but she sure keeps talking about it. My rating: n/a. Daughter's rating: A+
2. The Light Fantastic
: The first Terry Pratchett book I bought, because I had read a review of it in an old Dragon magazine. Yes, I'm that much of a geek -- no need to talk any further about it. Very funny book, as just about everyone who I've ever lent it to will insist. Skewers that highfalootin' fantasy genre, which can get a bit full of itself at times. My rating: A+
3. Another Fine Myth/Myth Conceptions 2-in1 (Myth 2-in-1)
: Another book I bought based off of a review I read in Dragon magazine. Yes, yes, I know. Geek. Anyway, very good stuff here, very ... uh, punny. Re-read it last year after the author, Robert Asprin, passed away. My rating: A
4. Colloquial Russian: The Complete Course for Beginners (Colloquial Series)
: An odd selection off the shelf. I was, at one time or another, a linguistics major in college. I picked up all sorts of language books -- German, Latin, Russian, Danish, Old English, even Sanskrit. Eventually, I wandered over into the world of computer science, where my fascination with languages continued on with books on Java, Python, C, C++, and Perl. Once a linguaphile, always a linguaphile. My rating: B+
5. The Path Into Darkness: Hey, the Web wouldn't be all about shameless self-promotion, if I didn't mention this book. Yes, I wrote it. I also have a hardcover copy of it on the shelf, but since I'm only doing quick reviews on 5 items, I choose the paperback version. I like it. Hell, if I didn't like it, I wouldn't have finished writing it, re-reading it, and editing it. It's self-published, which I know some people dislike, but there's a very good reason for that -- but I'm not goind to tell y'all what that is. My rating: A-. (Ha! You expected me to give myself an A+, didn't you? C'mon, fess up...)
Well, there you go ... 5 items off the shelf, reviewed, and then they'll be going back onto the shelf a few minutes after I click on the "Publish Post" button.
Stay tuned for another riveting chapter in "Stuff In Steve's Apartment" continues...
1. Diary of a Wimpy Kid
2. The Light Fantastic
3. Another Fine Myth/Myth Conceptions 2-in1 (Myth 2-in-1)
4. Colloquial Russian: The Complete Course for Beginners (Colloquial Series)
5. The Path Into Darkness: Hey, the Web wouldn't be all about shameless self-promotion, if I didn't mention this book. Yes, I wrote it. I also have a hardcover copy of it on the shelf, but since I'm only doing quick reviews on 5 items, I choose the paperback version. I like it. Hell, if I didn't like it, I wouldn't have finished writing it, re-reading it, and editing it. It's self-published, which I know some people dislike, but there's a very good reason for that -- but I'm not goind to tell y'all what that is. My rating: A-. (Ha! You expected me to give myself an A+, didn't you? C'mon, fess up...)
Well, there you go ... 5 items off the shelf, reviewed, and then they'll be going back onto the shelf a few minutes after I click on the "Publish Post" button.
Stay tuned for another riveting chapter in "Stuff In Steve's Apartment" continues...
Labels:
books,
miscellaneous,
reviews,
stuff in my apartment
Saturday, September 20, 2008
Metallica's Death Magnetic is ... well ... pretty damn good.
This isn't usually a music review site, but I picked up Metallica's new album, Death Magnetic
I was skeptical, what with having been disappointed by St. Anger
I popped the CD into my car's player and listened to it on the drive to and from work. Then again did the same the next day. There's a lot of goodness in the tracks, although the quality of the sound is ... poor. There are four "pure good" songs on the album, which I've taken the liberty of putting into the Amazon MP3 player so you can get the feel for them.
- The opening track, "That Was Just Your Life", is incredibly good. Fast, crunchy guitar. Interesting singing.
- The first single, "The Day That Never Comes", starts slow and ends fast. It reminds me somewhat of something like One or Fade to Black, but without reaching their slowness.
- "All Nightmare Long" is just plain awesome. I love that chorus of "Hunt you down without mercy"
- "My Apocalypse" is an awesome way to end the album. It's fast and lots of violent, death imagery without the cartooniness rampant in today's "modern" heavy metal.
The world could have done without "The Unforgiven III", which is the only clunker on the album. Overall, it's a massive step in the right direction for the band -- their last few studio works had more clunkers than gems. I think it fits firmly into the sort of work they should have put out following ...And Justice for All
Overall, I have to give this one 4 out of 5 stars. It's no Master of Puppets
(Yes, I know that I whored this review up with Amazon links. Hey, guy's gotta eat, you know.)
Subscribe to:
Posts (Atom)