Text stringlengths 1 9.41k |
|---|
# C = Decorator(C)
x = C()
y = C() # Overwrites x!
```
This code handles multiple decorated classes (each makes a new Decorator instance)
and will intercept instance creation calls (each runs __call__). |
Unlike the prior version,
however, this version fails to handle multiple instances of a given class—each instance
creation call overwrites the prior saved instance. |
The original version does support
multiple instances, because each instance creation call makes a new independent wrapper object. |
More generally, either of the following patterns supports multiple wrapped
instances:
```
def decorator(C): # On @ decoration
class Wrapper:
def __init__(self, *args): # On instance creation
self.wrapped = C(*args)
return Wrapper
class Wrapper: ...
def decorator(C): ... |
To support multiple steps of augmentation,
decorator syntax allows you to add multiple layers of wrapper logic to a decorated
function or method. |
When this feature is used, each decorator must appear on a line
of its own. |
Decorator syntax of this form:
```
@A
@B
@C
def f(...):
...
```
runs the same as the following:
```
def f(...):
...
f = A(B(C(f)))
```
Here, the original function is passed through three different decorators, and the resulting callable object is assigned back to the original name. |
Each decorator processes
the result of the prior, which may be the original function or an inserted wrapper.
If all the decorators insert wrappers, the net effect is that when the original function
name is called, three different layers of wrapping object logic will be invoked, to augment the original function in thre... |
The last decorator listed is the first
applied, and the most deeply nested (insert joke about “interior decorators” here...).
Just as for functions, multiple class decorators result in multiple nested function calls,
and possibly multiple levels of wrapper logic around instance creation calls. |
For example, the following code:
```
@spam
@eggs
class C:
...
X = C()
```
is equivalent to the following:
```
class C:
...
C = spam(eggs(C))
X = C()
```
Again, each decorator is free to return either the original class or an inserted wrapper
object. |
With wrappers, when an instance of the original C class is finally requested, the
call is redirected to the wrapping layer objects provided by both the `spam and` `eggs`
decorators, which may have arbitrarily different roles.
**|**
-----
For example, the following do-nothing decorators simply return the decorated
f... |
When designed well, decorator nesting allows us to combine
augmentation steps in a wide variety of ways.
###### Decorator Arguments
Both function and class decorators can also seem to take arguments, although really
these arguments are passed to a callable that in effect returns the decorator, which in
turn returns a... |
The following, for instance:
```
@decorator(A, B)
def F(arg):
...
F(99)
```
is automatically mapped into this equivalent form, where decorator is a callable that
returns the actual decorator. |
The returned decorator in turn returns the callable run
later for calls to the original function name:
**|**
-----
```
def F(arg):
...
F = decorator(A, B)(F) # Rebind F to result of decorator's return value
F(99) # Essentially calls decorator(A, B)(F)(99)
```
Decorator arguments are resolved b... |
The decorator function in this
example, for instance, might take a form like the following:
```
def decorator(A, B):
```
_# Save or use A, B_
```
def actualDecorator(F):
```
_# Save or use function F_
_# Return a callable: nested def, class with __call__, etc._
```
return callable
return actualDecorat... |
This
code snippet retains the state information argument in enclosing function scope references, but class attributes are commonly used as well.
In other words, decorator arguments often imply three levels of callables: a callable to
accept decorator arguments, which returns a callable to serve as decorator, which ret... |
Each of the three levels
may be a function or class and may retain state in the form of scopes or class attributes.
We’ll see concrete examples of decorator arguments employed later in this chapter.
###### Decorators Manage Functions and Classes, Too
Although much of the rest of this chapter focuses on wrapping later... |
As such, it can also be used to invoke arbitrary post-creation
processing:
```
def decorate(O):
```
_# Save or augment function or class O_
```
return O
@decorator
def F(): ... |
# F = decorator(F)
@decorator
class C: ... |
# C = decorator(C)
```
As long as we return the original decorated object this way instead of a wrapper, we
can manage functions and classes themselves, not just later calls to them. |
We’ll see
more realistic examples later in this chapter that use this idea to register callable objects
to an API with decoration and assign attributes to functions when they are created.
**|**
-----
###### Coding Function Decorators
On to the code—in the rest of this chapter, we are going to study working example... |
This section presents a
handful of function decorators at work, and the next shows class decorators in action.
Following that, we’ll close out with some larger case studies of class and function decorator usage.
###### Tracing Calls
To get started, let’s revive the call tracer example we met in Chapter 31. |
The following
defines and applies a function decorator that counts the number of calls made to the
decorated function and prints a trace message for each call:
```
class tracer:
def __init__(self, func): # On @ decoration: save original func
self.calls = 0
self.func = func
def __call__(self,... |
Also observe how the `*args argument`
syntax is used to pack and unpack arbitrarily many passed-in arguments. |
This generality enables this decorator to be used to wrap any function with any number of arguments (this version doesn’t yet work on class methods, but we’ll fix that later in this
section).
Now, if we import this module’s function and test it interactively, we get the following
sort of behavior—each call generates a... |
This code runs under both Python 2.6 and 3.0, as does all code in
this chapter unless otherwise noted:
```
>>> from decorator1 import spam
```
`>>> spam(1, 2, 3)` _# Really calls the tracer wrapper object_
```
call 1 to spam
6
```
`>>> spam('a', 'b', 'c')` _# Invokes __call__ in class_
```
call 2 to spam
ab... |
Notice how the
total number of calls shows up as an attribute of the decorated function—spam is really
an instance of the tracer class when decorated (a finding that may have ramifications
for programs that do type checking, but is generally benign).
For function calls, the @ decoration syntax can be more convenient t... |
Consider a nondecorator equivalent such as the following:
```
calls = 0
def tracer(func, *args):
global calls
calls += 1
print('call %s to %s' % (calls, func.__name__))
func(*args)
def spam(a, b, c):
print(a, b, c)
```
`>>> spam(1, 2, 3)` _# Normal non-traced call: accidental?_
```
1 2 3
`... |
Although decorators are never _re-_
_quired (we can always rebind names manually), they are often the most convenient_
option.
###### State Information Retention Options
The last example of the prior section raises an important issue. |
Function decorators
have a variety of options for retaining state information provided at decoration time,
for use during the actual function call. |
They generally need to support multiple decorated objects and multiple calls, but there are a number of ways to implement these
goals: instance attributes, global variables, nonlocal variables, and function attributes
can all be used for retaining state.
**|**
-----
###### Class instance attributes
For example, he... |
Both the_
wrapped function and the calls counter are per-instance information—each decoration
gets its own copy. |
When run as a script under either 2.6 or 3.0, the output of this version
is as follows; notice how the spam and eggs functions each have their own calls counter,
because each decoration creates a new class instance:
```
call 1 to spam
6
call 2 to spam
15
call 1 to eggs
65536
call 2 to eggs
256
```
Whil... |
In this example, though, we
would also need a counter in the enclosing scope that changes on each call, and that’s
**|**
-----
not possible in Python 2.6. |
In 2.6, we can either use classes and attributes, as we did
earlier, or move the state variable out to the global scope, with global declarations:
```
calls = 0
def tracer(func): # State via enclosing scope and global
def wrapper(*args, **kwargs): # Instead of class attributes
global calls... |
Unlike
class instance attributes, global counters are cross-program, not per-function—the
counter is incremented for any traced function call. |
You can tell the difference if you
compare this version’s output with the prior version’s—the single, shared global call
counter is incorrectly updated by calls to every decorated function:
```
call 1 to spam
6
call 2 to spam
15
call 3 to eggs
65536
call 4 to eggs
256
###### Enclosing scopes and nonloc... |
If we really want a
_per-function counter, though, we can either use classes as before, or make use of the_
new `nonlocal statement in Python 3.0, described in` Chapter 17. |
Because this new
statement allows enclosing function scope variables to be changed, they can serve as
per-decoration and changeable data:
```
def tracer(func): # State via enclosing scope and nonlocal
calls = 0 # Instead of class attrs or global
def wrapper(*args, **kwargs): # calls... |
Here’s the new
output when run under 3.0:
```
call 1 to spam
6
call 2 to spam
15
call 1 to eggs
65536
call 2 to eggs
256
###### Function attributes
```
Finally, if you are not using Python 3.X and don’t have a nonlocal statement, you may
still be able to avoid globals and classes by making use of func... |
In recent Pythons, we can assign arbitrary attributes to functions to attach them, with `func.attr=value. In our example, we can simply use`
```
wrapper.calls for state. |
The following works the same as the preceding nonlocal ver
```
sion because the counter is again per-decorated-function, but it also runs in Python 2.6:
```
def tracer(func): # State via enclosing scope and func attr
def wrapper(*args, **kwargs): # calls is per-function, not global
wrapper.cal... |
When we later increment wrapper.calls, we are not changing
```
the name wrapper itself, so no nonlocal declaration is required.
**|**
-----
This scheme was almost relegated to a footnote, because it is more obscure than
```
nonlocal in 3.0 and is probably better saved for cases where other schemes don’t help.
```... |
As we’ll see later, though, this sometimes may be subtler than you expect—each
decorated function should have its own state, and each decorated class may require
state both for itself and for each generated instance.
In fact, as the next section will explain, if we want to apply function decorators to class
methods, t... |
Unfortunately, I was wrong: when applied to a class’s method, the first version of the
```
tracer fails, because self is the instance of the decorator class and the instance of the
```
decorated subject class in not included in *args. |
This is true in both Python 3.0 and 2.6.
I introduced this phenomenon earlier in this chapter, but now we can see it in the
context of realistic working code. |
Given the class-based tracing decorator:
```
class tracer:
def __init__(self, func): # On @ decorator
self.calls = 0 # Save func for later call
self.func = func
def __call__(self, *args, **kwargs): # On call to original function
self.calls += 1
print('call %s to %s'... |
We really need both as it’s coded:
the tracer for decorator state, and the Person for routing on to the original method.
Really, self _must be the tracer object, to provide access to tracer’s state information;_
this is true whether decorating a simple function or a method.
Unfortunately, when our decorated method nam... |
Moreover, because the `tracer knows`
nothing about the Person instance we are trying to process with method calls, there’s
no way to create a bound method with an instance, and thus no way to correctly dispatch the call.
In fact, the prior listing winds up passing too few arguments to the decorated method,
and results... |
Add a line to the decorator’s __call__ to print all its arguments
to verify this; as you can see, self is the tracer, and the Person instance is entirely absent:
```
<__main__.tracer object at 0x02D6AD90> (0.25,) {}
call 1 to giveRaise
Traceback (most recent call last):
File "C:/misc/tracer.py", line 56, in <m... |
Technically, Python only
makes a bound method object containing the subject instance when the method is a
simple function.
**|**
-----
###### Using nested functions to decorate methods
If you want your function decorators to work on both simple functions and class methods, the most straightforward solution lies in... |
Because decorated
methods are rebound to simple functions instead of instance objects, Python correctly
passes the Person object as the first argument, and the decorator propagates it on in the
first item of *args to the self argument of the real, decorated methods:
_# A decorator for both functions and methods_
```
... |
The descriptor feature we explored in the prior chapter,
for example, can help here as well.
Recall from our discussion in that chapter that a descriptor may be a class attribute
assigned to objects with a `__get__ method run automatically when that attribute is`
referenced and fetched (object derivation is required i... |
Now, because the descriptor’s __get__ method receives both the descriptor
class and subject class instances when invoked, it’s well suited to decorating methods
when we need both the decorator’s state and the original class instance for dispatching
calls. |
Consider the following alternative tracing decorator, which is also a descriptor:
```
class tracer(object):
def __init__(self, func): # On @ decorator
self.calls = 0 # Save func for later call
self.func = func
def __call__(self, *args, **kwargs): # On call to original func
... |
Decorated functions
invoke only its __call__, while decorated methods invoke its __get__ first to resolve
the method name fetch (on instance.method); the object returned by __get__ retains
the subject class instance and is then invoked to complete the call expression, thereby
triggering __call__ (on (args...)). |
For example, the test code’s call to:
```
sue.giveRaise(.10) # Runs __get__ then __call__
```
run’s tracer.__get__ first, because the giveRaise attribute in the Person class has been
rebound to a descriptor by the function decorator. |
The call expression then triggers the
```
__call__ method of the returned wrapper object, which in turn invokes
tracer.__call__.
```
The wrapper object retains both descriptor and subject instances, so it can route control
back to the original decorator/descriptor class instance. |
In effect, the wrapper object
saves the subject class instance available during method attribute fetch and adds it to
the later call’s arguments list, which is passed to __call__. |
Routing the call back to the
descriptor class instance this way is required in this application so that all calls to a
wrapped method use the same calls counter state information in the descriptor instance object.
Alternatively, we could use a nested function and enclosing scope references to achieve
the same effect—t... |
In either coding, this descriptor-based scheme is also substantially subtler than the nested function option, and so is probably a second choice
here; it may be a useful coding pattern in other contexts, though.
In the rest of this chapter we’re going to be fairly casual about using classes or functions
to code our fu... |
Some
decorators may not require the instance of the original class, and will still work on both
functions and methods if coded as a class—something like Python’s own
```
staticmethod decorator, for example, wouldn’t require an instance of the subject class
```
(indeed, its whole point is to remove the instance from th... |
Our next decorator times calls made to a decorated function—both
the time for one call, and the total time among all calls. |
The decorator is applied to two
functions, in order to compare the time requirements of list comprehensions and the
```
map built-in call (for comparison, also see Chapter 20 for another nondecorator example
```
that times iteration alternatives like these):
```
import time
class timer:
def __init__(self, func... |
Hence,
3.0’s map doesn’t quite compare directly to a list comprehension’s work (as is, the map
test takes virtually no time at all in 3.0!).
If you wish to run this under 3.0, too, use list(map()) to force it to build a list like the
list comprehension does, or else you’re not really comparing apples to apples. |
Don’t
do so in 2.6, though—if you do, the map test will be charged for building two lists, not
one.
The following sort of code would pick fairly for 2.6 and 3.0; note, though, that while
this makes the comparison between list comprehensions and map more fair in either 2.6
**|**
-----
or 3.0, because range is also ... |
We won’t do this, though, because we’re about to add another
feature to our code.
###### Adding Decorator Arguments
The timer decorator of the prior section works, but it would be nice if it was more
configurable—providing an output label and turning trace messages on and off, for
instance, might be useful in a gener... |
Decorator arguments come
in handy here: when they’re coded properly, we can use them to specify configuration
options that can vary for each decorated function. |
A label, for instance, might be added
as follows:
```
def timer(label=''):
def decorator(func):
def onCall(*args): # args passed to function
... |
# func retained in enclosing scope
print(label, ... |
# label retained in enclosing scope
return onCall
return decorator # Returns that actual decorator
@timer('==>') # Like listcomp = timer('==>')(listcomp)
def listcomp(N): ... |
# listcomp is rebound to decorator
listcomp(...) # Really calls decorator
```
This code adds an enclosing scope to retain a decorator argument for use on a later
actual call. |
When the listcomp function is defined, it really invokes decorator (the result
of timer, run before decoration actually occurs), with the label value available in its
enclosing scope. |
That is, `timer` _returns the decorator, which remembers both the_
**|**
-----
decorator argument and the original function and returns a callable which invokes the
original function on later calls.
We can put this structure to use in our timer to allow a label and a trace control flag to
be passed in at decoratio... |
Here’s an example that does just that, coded in a
module file named mytools.py so it can be imported as a general tool:
```
import time
def timer(label='', trace=True): # On decorator args: retain args
class Timer:
def __init__(self, func): # On @: retain decorated func
self.func ... |
The outer timer function
is called before decoration occurs, and it simply returns the Timer class to serve as the
actual decorator. |
On decoration, an instance of Timer is made that remembers the decorated function itself, but also has access to the decorator arguments in the enclosing
function scope.
This time, rather than embedding self-test code in this file, we’ll run the decorator in
a different file. |
Here’s a client of our timer decorator, the module file testseqs.py, applying it to sequence iteration alternatives again:
```
from mytools import timer
@timer(label='[CCC]==>')
def listcomp(N): # Like listcomp = timer(...)(listcomp)
return [x * 2 for x in range(N)] # listcomp(...) triggers Ti... |
When
run as-is in 2.6, this file prints the following output—each decorated function now has
a label of its own, defined by decorator arguments:
```
[CCC]==> listcomp: 0.00003, 0.00003
[CCC]==> listcomp: 0.00640, 0.00643
[CCC]==> listcomp: 0.08687, 0.09330
[CCC]==> listcomp: 0.17911, 0.27241
[0, 2, 4, 6, 8]
... |
def listcomp(N):
... |
return [x * 2 for x in range(N)]
...
>>> x = listcomp(5000)
>>> x = listcomp(5000)
>>> x = listcomp(5000)
>>> listcomp
<mytools.Timer instance at 0x025C77B0>
>>> listcomp.alltime
0.0051938863738243413
```
`>>> @timer(trace=True, label='\t=>')` _# Turn on tracing_
```
... |
def listcomp(N):
... |
return [x * 2 for x in range(N)]
...
>>> x = listcomp(5000)
=> listcomp: 0.00155, 0.00155
>>> x = listcomp(5000)
=> listcomp: 0.00156, 0.00311
>>> x = listcomp(5000)
=> listcomp: 0.00174, 0.00486
>>> listcomp.alltime
0.0048562736325408196
```
This timing function decorator can be used for... |
In other words, it automatically qualifies as a _general-purpose tool for_
timing code in our scripts. |
Watch for another example of decorator arguments in the
**|**
-----
section “Implementing Private Attributes” on page 1023, and again in “A Basic RangeTesting Decorator for Positional Arguments” on page 1035.
_Timing methods: This section’s timer decorator works on any function,_
but a minor rewrite is required to... |
In short, as our earlier section “Class Blunders I: Decorating Class
Methods” on page 1001 illustrated, it must avoid using a nested class.
Because this mutation will be a subject of one of our end-of-chapter quiz
questions, though, I’ll avoid giving away the answer completely here.
###### Coding Class Decorators
So ... |
As described earlier,
while similar in concept to function decorators, class decorators are applied to classes
instead—they may be used either to manage classes themselves, or to intercept instance
creation calls in order to manage instances. |
Also like function decorators, class decorators are really just optional syntactic sugar, though many believe that they make a
programmer’s intent more obvious and minimize erroneous calls.
###### Singleton Classes
Because class decorators may intercept instance creation calls, they can be used to either
manage all t... |
To
demonstrate, here’s a first class decorator example that does the former—managing all
instances of a class. |
This code implements the classic singleton coding pattern, where
at most one instance of a class ever exists. |
Its singleton function defines and returns a
function for managing instances, and the @ syntax automatically wraps up a subject
class in this function:
```
instances = {}
def getInstance(aClass, *args): # Manage global table
if aClass not in instances: # Add **kargs for keywords
instances[... |
Here’s this code’s output:
```
Bob 400
Bob 400
42 42
```
Interestingly, you can code a more self-contained solution here if you’re able to use the
```
nonlocal statement (available in Python 3.0 and later) to change enclosing scope names,
```
as described earlier—the following alternative achieves an identical ... |
In either Python 2.6 or 3.0, you can also code a self-contained
solution with a class instead—the following uses one instance per class, rather than an
enclosing scope or global table, and works the same as the other two versions (in fact,
it relies on the same coding pattern that we will later see is a common decorato... |
Another common use case for class decorators augments_
the interface of each generated instance. |
Class decorators can essentially install on instances a wrapper logic layer that manages access to their interfaces in some way.
For example, in Chapter 30, the __getattr__ operator overloading method is shown as
a way to wrap up entire object interfaces of embedded instances, in order to implement
the delegation codi... |
We saw similar examples in the managed attribute coverage of the prior chapter. |
Recall that __getattr__ is run when an undefined attribute
name is fetched; we can use this hook to intercept method calls in a controller class
and propagate them to an embedded object.
For reference, here’s the original nondecorator delegation example, working on two
built-in type objects:
```
class Wrapper:
d... |
Specifically, it traces attribute accesses made outside the wrapped object’s class; accesses inside the wrapped object’s methods are not caught and run normally by design. |
This whole-interface model differs from the behavior of function decorators, which wrap up just one specific method.
**|**
-----
Class decorators provide an alternative and convenient way to code this __getattr__
technique to wrap an entire interface. |
In 2.6 and 3.0, for example, the prior class example can be coded as a class decorator that triggers wrapped instance creation, instead
of passing a pre-made instance into the wrapper’s constructor (also augmented here to
support keyword arguments with **kargs and to count the number of accesses made):
```
def Tracer... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.