De-nesting decorators in python

April 6, 2009 at 9:45 pm Leave a comment

Definitions of decorators are quite nested

def decorate(f):
    def patched(*args, **kwargs):
        # do stuff involving f
    return patched

About 25% I also forget to write the final “return patched”.

One way to work around this is to write a ‘denest decorator decorator’ so you can write the following as an alternative to the above:

@denest
def decorate(f, *args, *kwargs):
    # do stuff involving f   

This has the disadvantage that you can’t perform operations at the time of decoration – but it simplifies code slightly for the standard case (at the cost of making your code less idiomatic).

The denest decorator is defined like this:

def denest(func):
     def decorate(f):
           def patched(*args, **kwargs):
               return func(f, *args, **kwargs)
            return patched
     return decorate

Example usage:

A decorator that converts converts a function which could raise an Excpetion into a function which returns None on error.

@denest
def makeIntoTry(f, *args, **kwargs):
    try:
        return f(*args, **kwargs)
    except Exception:
        return None
Advertisements

Entry filed under: Uncategorized.

Python generator to list decorator Reading files in factor

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Trackback this post  |  Subscribe to the comments via RSS Feed


April 2009
M T W T F S S
« Mar   May »
 12345
6789101112
13141516171819
20212223242526
27282930  

%d bloggers like this: