decorat{or,ion}

Mike McClain mike.junk.46 at att.net
Sat May 19 21:36:20 EDT 2018


On Sat, May 19, 2018 at 07:22:28AM +0000, Steven D'Aprano wrote:
> On Fri, 18 May 2018 18:31:16 -0700, Mike McClain wrote:
>
<snip>
> I *think* you are describing something like this:
Real close!
> def foo(x):
>     return x + 1
>
> def bar(arg):
>     a = baz(arg)  # do some magic
>     result = bar(a)  # call the important function
      result = foo(a)  #                    small change
>     return buz(result)  # and a bit more magic

<snip>

> 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

Too early to tell. Your definition of factory returns a function ref
so needs assignment unless used (execd) immediately. Yes, no?

def factory(func):
    # Wrap func() to a different kind of magic
    def bar(arg):
        a = baz(arg)  # do some magic
        result = func(a)  #                    small change
        return buz(result)  # and a bit more magic
    return bar

@factory
def foo(x):
    return something_outrageous

At this point it looks to me that I've created a nameless function
that can't be used. How does the assignment take place?

> Does this help?

If I've understood you correctly it helps one Heck of a lot.
If I haven't, no doubt the fault is mine.
I've used several procedural languages but you OOP folk think in
strange paths. So far it is a fun trip.

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

Walk with Light,
Mike
--
    I am going to go stand outside so if anyone asks about me,
        tell them I'M OUTSTANDING!



More information about the Python-list mailing list