Python Snippet: Converting a complex object to json

Aside

Here’s a simple recipe, to convert most Python class-objects to json and back.

Here’s the setup:

import json

class Foo:
    def __init__(self, name, values):
        self.name = name
        self.values = values

Converting to json:

an_object = Foo('John', (123, 456, 789))

json_string = json.dumps(vars(an_object))

Quite simple, isn’t it? Using the vars function, Python converts the object to a dictionary which can then be jsonified, using the json.dums function.

The reverse is quite simple as well:

a_fresh_object = Foo(**json.loads(json_string))

This simply takes the output of json.loads, which is a dict, and maps the keys and values of that dict to the names arguments of Foo’s __init__ method.

Nifty.

So long…

Advertisements

Writing Python Function Decorators

Python has a pretty neat way, of letting you write function decorators.

A Function decorator in general, alters or appends to the functionality performed by the decorated method, without having to directly depend on or know it.

Thus it is possible, to use decorators to declare aspects, without re-writing the same code over and over again.

In python, you can decorate a function by using the following syntax:

@my_decorator(argument='value')
def my_function(arg1, arg2):
    print "Something with %s and %s" % (arg1, arg2)

By doing that, python exchanges any calls to your method, by calls to the decorator, defined as my_decorator. This decorator can now decide, to do some additional work and (if wanted) call the original function.

To define a decorator, you have to write a function factory. That is a function, that defines and returns another function, that can be called with the original function as an argument.

def my_decorator(argument):
    def outer_wrapper(original_method):
        # This code gets called, when the decorated
        # function gets defined

        def inner_wrapper(*args, **kwargs):
            # This method gets called, instead of the
            # actual function call to the decorated
            # function.
            print "I come from before the function"
            return_value = original_method(args, kwargs)
            print "The method returned %s" % return_value
            return return_value

        return inner_wrapper
    return outer_wrapper

Have fun.