Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>There are two ways of doing it. The object-oriented way is to make a class:</p> <pre><code>class max_execs: def __init__(self, max_executions): self.max_executions = max_executions self.executions = 0 def __call__(self, func): @wraps(func) def maybe(*args, **kwargs): if self.executions &lt; self.max_executions: self.executions += 1 return func(*args, **kwargs) else: print "fail" return maybe </code></pre> <p>See <a href="https://stackoverflow.com/questions/308999/what-does-functools-wraps-do">this question</a> for an explanation of <code>wraps</code>.</p> <p>I prefer the above OOP approach for this kind of decorator, since you've basically got a private count variable tracking the number of executions. However, the other approach is to use a closure, such as</p> <pre><code>def max_execs(max_executions): executions = [0] def actual_decorator(func): @wraps(func) def maybe(*args, **kwargs): if executions[0] &lt; max_executions: executions[0] += 1 return func(*args, **kwargs) else: print "fail" return maybe return actual_decorator </code></pre> <p>This involved three functions. The <code>max_execs</code> function is given a parameter for the number of executions and returns a decorator that will restrict you to that many calls. That function, the <code>actual_decorator</code>, does the same thing as our <code>__call__</code> method in the OOP example. The only weirdness is that since we don't have a class with private variables, we need to mutate the <code>executions</code> variable which is in the outer scope of our closure. Python 3.0 supports this with the <code>nonlocal</code> statement, but in Python 2.6 or earlier, we need to wrap our executions count in a list so that it can be mutated.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload