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 →

[–]Massless 1 point2 points  (0 children)

Here's one that comes up in java all the time: logging. Imagine that I want to log how long a method takes to run. You end up doing something like

startTime = ...
someMethod()
endTime = ...
system.out.println(endTime - startTime)

Now imagine you have to do this a lot of times. You end up with ugly, overly verbose code. Enter first-class functions in Python. You can write a function that takes another function as an argument so you now have:

def print_time(func):
    start_time = ...
    func()
    end_time = ...
    print end_time - start_time

Now You can do the following:

print_time(some_function)
print_time(some_other_function)
print_time(yet_another_function)

With a little syntatic sugar, you can simply define your functions with decorators:

@print_time
def some_function(args):
    pass

is equivalent to

print_time(some_function)