decorat{or,ion}

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sat May 19 03:22:28 EDT 2018


On Fri, 18 May 2018 18:31:16 -0700, Mike McClain wrote:

> Let's say I want something that does most or all of foo's functionality
> plus a little more and maybe tweek some of foo's output, so I write a
> wrapper around foo and call it bar. If inside bar are the call to foo,
> as well as methods baz(), buz() and bug() that make their magic and bar
> ends up performing as I want.

I *think* you are describing something like this:

def foo(x):
    return x + 1

def bar(arg):
    a = baz(arg)  # do some magic
    result = bar(a)  # call the important function
    return buz(result)  # and a bit more magic


No methods are required! We can simply talk about ordinary functions.

(Methods are, in a sense, just like normal functions except they carry 
around some extra state, namely the object that owns them.)

Is that what you mean?


>     If I understood correctly baz(), buz() and bug() plus the glue
> that is bar are decorations around foo or bar is a decorator of foo.

Typically, we wouldn't use the term "decorator" or "decoration" to 
describe a hand-written function like bar(), even if it calls foo(). 
Normally the "decorator" terminology is reserved for one of two things:

(1) The software design pattern of using a factory function to "wrap" one 
function inside an automatically generated wrapper function that provides 
the extra additional functionality:


def factory(func):
    # Wrap func() to force it to return zero instead of negative
    def wrapped(arg):
        result = func(arg)
        if result < 0:
            result = 0
        return result
    # return the wrapped function
    return wrapped


(2) the syntax for applying such a factory function:

@factory
def myfunction(x):
    return 5 - x


Does this help?

I know these concepts are sometimes tricky. Concrete examples often make 
them easier to understand. Feel free to ask more questions as needed.


-- 
Steve




More information about the Python-list mailing list