How are these type of python decorators written in Python Programming Language?

editAnswer

reportReport

Answer(s) available: 1

Kalika Gour

, Foreign Exchange Trader, Financial Services Analyze Data

"

This is what I whipped up. It doesn't use a class, but it does use function attributes:

"
def max_execs(n=5):"
    def decorator(fn):"
        fn.max = n"
        fn.called = 0"
        def wrapped(*args, **kwargs):"
            fn.called += 1"
            if fn.called <= fn.max:"
                return fn(*args, **kwargs)"
            else:"
                # Replace with your own exception, or something"
                # else that you want to happen when the limit"
                # is reached"
                raise RuntimeError("max executions exceeded")"
        return wrapped"
    return decorator"
"

max_execs returns a functioned called decorator, which in turn returns wrapped. decoration stores the max execs and current number of execs in two function attributes, which then get checked in wrapped.

"

Translation: When using the decorator like this:

"
@max_execs(5)"
def f():"
    print "hi!""
"

You're basically doing something like this:

"
f = max_execs(5)(f)"
"

thumb_upUpvote10

smsComment

reportReport