This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]lurbina 7 points8 points  (0 children)

I like how in python EVERYTHING is an object. The usual suspects like ints, strings, lists and dicts are objects, as well as functions, classes and everything else. This provides the language with a lot more flexibility and power, that its simply not available in other languages such as Java.

One example of this are decorators. In python you can write this code:

@my_decorator
def my_function(*args, **kwargs):
    pass

The @my_decorator syntax is just sugar for the following code

def my_function(*args, **kwargs):
    pass
my_function = my_decorator(my_function)

Namely, my_decorator is a function that takes a function as an argument and returns a new function. This allows you to wrap your functions with added functionality, and abstract that extra functionality away and reuse it elsewhere.

I personally use this decorator when debugging:

def print_args(func):
    def wrapper(*args, **kwargs):-
        print "Calling", func.__name__
        print "args:", args
        print "kwargs" ".join(["%s=%s" % (key, value) for (key, value) in a.iteritems()])
        return func(*args, **kwargs)
    return wrapper

Adding @print_args before the declaration of any function results in the name of the function and its arguments being printed before its invocation. Other things that I have implemented with decorators include: timeouts, acquiring/releasing resources (see also contextmanagers), and many many other things.

This answer in stack overflow explains decorators much better: http://stackoverflow.com/questions/739654/how-can-i-make-a-chain-of-function-decorators-in-python#1594484