Kurt Peek
Kurt Peek

Reputation: 57761

Meaning of the "@package" decorator in Python

I'm trying to understand a class method definition which reads similar to the following:

@package(type='accounts', source='system')
def get(self, [other arguments]):
    [function body]

What is the meaning of the @package decorator? I was unable to find documentation on this.

Upvotes: 0

Views: 188

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1124558

There is no default package decorator in the Python standard library.

A decorator is just a simple expression; there will be a package() callable in the same module (either defined there as a function or class, or imported from another module).

The line @package(type='accounts', source='system') executes the expression package(type='accounts', source='system'), and the return value of that is used to decorate the get() function. You could read it as:

def get(self, [other arguments]):
    [function body]
get = package(type='accounts', source='system')(get)

except the name get is set just once.

For example, package could be defined as:

def package(type='foo', source='bar'):
    def decorator(func):
        def wrapper(*args, **kwargs):
            # do something with type and source
            return func(*args, **kwargs)
        return wrapper
    return decorator

so package() returns decorator(), which in turn returns wrapper(); package() is a decorator factory, producing the actual decorator.

Upvotes: 3

Related Questions