Archive for April, 2009

Reading files in factor

Working code for the impatient

The following factor code reads and counts the number of words in the file “/etc/fstab”

USING: io.encodings.ascii io io.files prettyprint splitting sequences ;
"/etc/fstab" ascii file-contents " \n\t" split length .

See also

Official api docs.

April 10, 2009 at 7:08 pm Leave a comment

De-nesting decorators in python

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

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


April 2009
M T W T F S S
 12345
6789101112
13141516171819
20212223242526
27282930