Aspect-oriented Python

A friend asked me for an example of AOP in Python. I started to write up my response, then realized it might be worth sharing more widely.

Briefly, AOP is about separating out Aspects which are are interspersed throughout your code (in AOP lingo, cross-cutting). The canonical example is logging, but there are others.

For Python, as long as you’re content with before/after aspects, the situation is good. In Python 2.5 and up there are two main tactics: decorators and context managers. Decorators use the @ syntax and context managers are used with the “with” keyword.

Decorators

Decorators are only usable on functions and methods in 2.4 and 2.5, but in 2.6, 3.0 and beyond they can be used on classes as well. Essentially they are callables (functions, methods, objects) that accept a function object and return a function object. They are called when the function is defined, so they get a chance to have their way with it: annotate it, replace it, or wrap it. The common case is to wrap it.

Quick example:

import logging
def before(fn):
    def wrapped(*args, **kws):
        logging.warn('about to call function %s' % fn.func_name)
        return fn(*args, **kws)
    return wrapped

def after(fn):
    def wrapped(*args, **kws):
        retVal = fn(*args, **kws)
        logging.warn('just returned from function %s' % fn.func_name)
        return retVal
    return wrapped

OK, those are three basic wrappers, you can use them like so:

@before
def foo():
    logging.warn('inside foo')

@after
def bar():
    logging.warn('inside bar')

@before
@after
def baz():
    logging.warn('inside baz')

foo()
bar()
baz()

This will result in the following output:

WARNING:root:about to call function foo
WARNING:root:inside foo
WARNING:root:inside bar
WARNING:root:just returned from function bar
WARNING:root:about to call function wrapped
WARNING:root:inside baz
WARNING:root:just returned from function baz

You will note that when we use two decorators on baz, the name of the function called by before is “wrapped.” This is because what before is called on is the result of after. The functools.update_wrapper function is useful in this case to make a wrapped function look more like the original function.

For more, please see PEP 318 Decorators for Functions and Methods: Examples and PEP 3129 Class Decorators. For convenience when creating new decorators, see the standard library functions functools.update_wrapper and functools.wraps.

Context Managers

Context Managers are used with the with statement, and are handy for resource aquisition and release. In Python 2.5 you have to “from __future__ import with_statement” to use them, but they are built-in in Python versions later than that. Also, objects such as files and locks are context managers now, so you can use patterns like

with open('example.txt') as example:
    for line in example:
        do_something(line)

This will automatically close the file when leaving the with block. And for locks the pattern is similar:

with myThreadingLock:
    do_something_threadsafely()

It is important to note that the lock will be release properly, or the file closed, even if an exception is thrown inside the with block.

If you want to create your own context managers, you can add two methods to your objects: __enter__(self) and __exit__(self, exception_type, exception_value, traceback). The return value from __enter__ will be passed to the optional as variable (seen in the file example). The __exit__ method will be called with exception info if there was an exception. If no exception is raised in the with block, then all three arguements will be None. If __exit__ returns True then any exception will be “swallowed”, otherwise the exception will be re-raised after any cleanup.

For more info, see PEP 343 The “with” Statement, especially the examples section, and also the helper functions in the standard library contextlib.

AOP and 80/20

Full-on aspect-oriented programming is beyond the scope of this post and involves join-points, code weaving, and other such arcanery. There are multiple Python libraries which target aspect-oriented coding styles, but for my money, the simplicity of the methods in the standard library, coupled with my impression that they cover at least 80% of the uses of AOP, make me favour these built-in techniques over any of the special purpose tools.

Great works of art in social media

image_28_cropped.jpg

At Northern Voice, Darren Barefoot is asking why there is so little profound art on the web, but I think there is so much profound art that I cannot keep up with it. Perhaps it is because we have different filters for what is profound, but here are some sites that I frequently find art that speaks to me.

Dresden Codec: Dungeons and Discourse
http://dresdencodak.com/cartoons/dc_031.htm
http://dresdencodak.com/cartoons/dc_059.html

Industrial Decay
http://industrialdecay.blogspot.com/

NASA Astronomy Picture of the Day
http://apod.nasa.gov/apod/astropix.html

Algorithmic Art
Nodebox: http://nodebox.net/code/index.php/Gallery
Structure Synth: http://flickr.com/groups/structuresynth/
Processing: http://processing.org/exhibition/index.html

GapMinder (profound statistics)
http://www.gapminder.org/

Afrigadget
http://www.afrigadget.com/

Film is not dead, it just smells funny
http://www.thiaps.com/

BLDBLOG
http://bldgblog.blogspot.com/

We Make Money Not Art
http://www.we-make-money-not-art.com/

While I cannot keep up with all the art that I come across, I can find a social connection between all of these. The best, most moving art doesn’t just inspire me to admire it or think about it, but to share it with my friends and to create art that I wouldn’t have created otherwise.

Balding for Dollars: The Movie

This will be my last post on the topic for awhile. I just wanted to thank everyone who helped out: Julie, Joanna, David, Fiona, Daniela, Hashim, Wil, Frank, Berenice, Hashim, Jim, Judy, Keith, Mary, Mike, Rachel, Stewart, Mag, Tom, Vince, Angelina, and Anonymous. Together we met the goal and raised over $1000 for B.C. Children’s Hospital! Above is the documentary that Frank and Berenice made of the shave itself. And if you still haven’t had enough about balding for dollars, there are more videos on YouTube here.

Time to start thinking about the Northern Voice conference in two days! Hope to see you there!

Balding for Dollars Update

balding_after.jpg

Well, my Balding for Dollars event was a success. I have raised $717.37 for Children’s Hospital (there is still time to help bring it to my goal of $1000 if you’d like to donate). Thanks to everyone who helped with donations, words of support, and especially to Frank for his photography, to Berenice for helping with the cutting, to my wife Daniela for her encouragement and help, and to our kids for their patience. I couldn’t have done it without all of you.

There has been one change of plans. I had wanted to donate the hair to a Canadian foundation making wigs for kids with cancer, but couldn’t find it. Daniela’s google-fu skills were better and tomorrow my hair will go off to the Eva and Co. hair donation program. And to clarify, my daughter didn’t shave her head, we’re sending a ponytail from when she went from a long hairstyle to a short one.

Thanks also, to everyone who offered me a toque, but I’m well covered.

Balding for dollars

balding_profile2.jpg

I usually use this site to try to give back to the community, with Python and Javascript tutorials, software, and the occasional joke. Today I’m going to ask for something in return. On Saturday, February 14th, 2009 (Valentine’s Day, at least in the US and Canada) I will be shaving my head to raise money for Vancouver Children’s Hospital as part of their Balding for Dollars drive.

The picture above was taken today by my friend Frank Lee. As you can see, my hair is quite long. I’ll be sending my ponytail to Locks of Love, who make a wigs for kids who have lost their hair due to medical conditions. This is my second balding for dollars and will be the fourth ponytail I’ve donated, and my daughter is also donating her ponytail. As I get older, my hair isn’t growing in like it used to. This may be my last good ponytail to give, so with your help, I’d like to make a difference.

You can make donations on the Balding for Dollars site here. Saturday is only two days away, so be my valentine and help some kids!

I appreciate any help you can give. Check back on Monday for before/after photos. Thank you!

« Previous entries Next Page » Next Page »

google

google

asus