Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Decorators

Open in Colab

We’ve seen Python functions and objects. Today, we’ll breifly cover decorators, which are functions that wrap functions, and come with sytactic sugar which lets you write things like

@time_wrapper
def my_function(x):
    ...
    
y = my_function(x)
> 1.1 seconds elapsed.

Again, we want to write a function that wraps another function. We can define this as

Here’s how we might use our wrapper:

one problem with this is that we had to go through the trouble of wrapping the function. Instead, we can just write

This is interpreted like what we did above, but is a bit easier to read.

Another problem we may encounter is that we now can’t access the docstring we wrote

One way to solve this is to use the wraps decorator from the functools package.

now, we can access the metadata from generate_random3, such as the docstring

As you might guess, the @wraps decorator copies the class metadata from f to the inner_wrapper function.