Text stringlengths 1 9.41k |
|---|
This isn’t ideal because it creates some code
redundancy, especially compared to 2.6 solutions. |
However, it isn’t too major a coding
effort, can be automated to some extent with tools or superclasses, suffices to make
our decorator work in 3.0, and allows operator overloading names to be declared
```
Private or Public too (assuming each overloading method runs the failIf test
```
internally):
**|**
-----
```... |
Since every class
is new-style in 3.0, delegation-based code is more difficult (though not impossible) in
this release.
On the other hand, delegation wrappers could simply inherit from a common superclass that redefines operator overloading methods once, with standard delegation code.
Moreover, tools such as additiona... |
Though still not as simple as the 2.6 solution,
such techniques might help make 3.0 delegation classes more general.
###### Implementation alternatives: __getattribute__ inserts, call stack inspection
Although redundantly defining operator overloading methods in wrappers is probably
the most straightforward workaroun... |
We don’t have space to explore this issue
much further here, so investigating other potential solutions is relegated to a suggested
exercise. |
Because one dead-end alternative underscores class concepts well, though, it
merits a brief mention.
One downside of this example is that instance objects are not truly instances of the
original class—they are instances of the wrapper instead. |
In some programs that rely
**|**
-----
on type testing, this might matter. |
To support such cases, we might try to achieve similar
effects by inserting a __getattribute__ method into the original class, to catch every
attribute reference made on its instances. |
This inserted method would pass valid
requests up to its superclass to avoid loops, using the techniques we studied in the prior
chapter. |
Here is the potential change to our class decorator’s code:
_# trace support as before_
```
def accessControl(failIf):
def onDecorator(aClass):
def getattributes(self, attr):
trace('get:', attr)
if failIf(attr):
raise TypeError('private attribute fetch: ' + attr)
else:
... |
For example,
it handles only attribute _fetches—as is, this version allows private names to be_ _as-_
_signed freely. |
Intercepting assignments would still have to use __setattr__, and either_
an instance wrapper object or another class method insertion. |
Adding an instance
wrapper to catch assignments would change the type again, and inserting methods fails
if the original class is using a __setattr__ of its own (or a __getattribute__, for that
matter!). |
An inserted __setattr__ would also have to allow for a __slots__ in the client
class.
In addition, this scheme does not address the _built-in operation attributes issue_
described in the prior section, since `__getattribute__ is not run in these contexts,`
either. |
In our case, if Person had a __str__ it would be run by print operations, but only
because it was actually present in that class. |
As before, the `__str__ attribute would`
_not be routed to the inserted __getattribute__ method generically—printing would_
bypass this method altogether and call the class’s __str__ directly.
Although this is probably better than not supporting operator overloading methods in
a wrapped object at all (barring redefini... |
Although most operator overloading methods are meant to be public, some might not be.
Much worse, because this nonwrapper approach works by adding a
```
__getattribute__ to the decorated class, it also intercepts attribute accesses made by
```
**|**
-----
_the class itself and validates them the same as accesses m... |
To know whether
an attribute access originated inside or outside the class, our method might need to
inspect frame objects on the Python call stack. |
This might ultimately yield a solution
(replace private attributes with properties or descriptors that check the stack, for example), but it would slow access further and is far too dark a magic for us to explore
here.
While interesting, and possibly relevant for some other use cases, this method insertion
technique d... |
We won’t explore this option’s coding pattern further here because we will study class augmentation techniques in the next chapter, in
conjunction with metaclasses. |
As we’ll see there, metaclasses are not strictly required
for changing classes this way, because class decorators can often serve the same role.
###### Python Isn’t About Control
Now that I’ve gone to such great lengths to add Private and Public attribute declarations for Python code, I must again remind you that it ... |
In fact, most Python programmers will probably
find this example to be largely or totally irrelevant, apart from serving as a demonstration of decorators in action. |
Most large Python programs get by successfully without
any such controls at all. |
If you do wish to regulate attribute access in order to eliminate
coding mistakes, though, or happen to be a soon-to-be-ex-C++-or-Java programmer,
most things are possible with Python’s operator overloading and introspection tools.
###### Example: Validating Function Arguments
As a final example of the utility of dec... |
It’s designed to be used during either development or
production, and it can be used as a template for similar tasks (e.g., argument type
testing, if you must). |
Because this chapter’s size limits has been broached, this example’s code is largely self-study material, with limited narrative; as usual, browse the
code for more details.
###### The Goal
In the object-oriented tutorial of Chapter 27, we wrote a class that gave a raise to objects
representing people based upon a pa... |
We could implement
such a check with either if or assert statements in the method itself, using inline tests:
```
class Person:
def giveRaise(self, percent): # Validate with inline code
if percent < 0.0 or percent > 1.0:
raise TypeError, 'percent invalid'
self.pay = int(self.pay * (1 + ... |
For more complex cases, this can become tedious
(imagine trying to inline the code needed to implement the attribute privacy provided
by the last section’s decorator). |
Perhaps worse, if the validation logic ever needs to
change, there may be arbitrarily many inline copies to find and update.
A more useful and interesting alternative would be to develop a general tool that can
perform range tests for us automatically, for the arguments of any function or method
we might code now or i... |
A _decorator approach makes this explicit and_
convenient:
```
class Person:
@rangetest(percent=(0.0, 1.0)) # Use decorator to validate
def giveRaise(self, percent):
self.pay = int(self.pay * (1 + percent))
```
Isolating validation logic in a decorator simplifies both clients and future maintena... |
Here, we mean to validate the values of function arguments
when passed, rather than attribute values when set. |
Python’s decorator and introspection tools allow us to code this new task just as easily.
###### A Basic Range-Testing Decorator for Positional Arguments
Let’s start with a basic range test implementation. |
To keep things simple, we’ll begin
by coding a decorator that works only for positional arguments and assumes they always appear at the same position in every call; they cannot be passed by keyword name,
and we don’t support additional **args keywords in calls because this can invalidate
the positions declared in the d... |
Code the following in a file called devtools.py:
```
def rangetest(*argchecks): # Validate positional arg ranges
def onDecorator(func):
if not __debug__: # True if "python -O main.py args..."
```
**|**
-----
```
return func # No-op: call original directly
else: ... |
When used for a class method, onCall receives the
subject class’s instance in the first item in *args and passes this along to self in the
original method function; argument numbers in range tests start at 1 in this case, not 0.
Also notice this code’s use of the __debug__ built-in variable, though—Python sets this
to... |
When __debug__ is False, the decorator returns the origin function un
```
changed, to avoid extra calls and their associated performance penalty.
This first iteration solution is used as follows:
_# File devtools_test.py_
```
from devtools import rangetest
print(__debug__) # False if "python –O main.... |
Assuming this is a debugging tool only, you
can use this flag to optimize your program for production use:
```
C:\misc> C:\python30\python –O devtools_test.py
False
Bob Smith is 45 years old
birthday = 5/31/1963
110000
231000
###### Generalizing for Keywords and Defaults, Too
```
The prior version illustr... |
Additionally, it does nothing about arguments
with defaults that may be omitted in a given call. |
That’s fine if all your arguments are
passed by position and never defaulted, but less than ideal in a general tool. |
Python
supports much more flexible argument-passing modes, which we’re not yet addressing.
**|**
-----
The mutation of our example shown next does better. |
By matching the wrapped function’s expected arguments against the actual arguments passed in a call, it supports
range validations for arguments passed by either position or keyword name, and it skips
testing for default arguments omitted in the call. |
In short, arguments to be validated
are specified by keyword arguments to the decorator, which later steps through both
the *pargs positionals tuple and the **kargs keywords dictionary to validate.
```
"""
File devtools.py: function decorator that performs range-test
validation for passed arguments. |
Arguments are specified by
keyword to the decorator. |
In the actual call, arguments may
be passed by position or keyword, and defaults may be omitted.
See devtools_test.py for example use cases.
"""
trace = True
def rangetest(**argchecks): # Validate ranges for both+defaults
def onDecorator(func): # onCall remembers func and argchecks
i... |
This code runs on both 2.6 and 3.0, but extra tuple parentheses print in 2.6.
Trace its output and test this further on your own to experiment; it works as before,
but its scope has been broadened:
```
C:\misc> C:\python30\python devtools_test.py
Bob is 40 years old
Bob is 40 years old
birthday = 5/1/1963
110... |
To be fully general we could in principle try to mimic Python’s argument matching logic in its entirety to see which names have been passed in which
**|**
-----
modes, but that’s far too much complexity for our tool. |
It would be better if we could
somehow match arguments passed by name against the set of all expected arguments’
names, in order to determine which position arguments actually appear in during a
given call.
###### Function introspection
It turns out that the introspection API available on function objects and their a... |
This API was briefly introduced in Chapter 19, but we’ll actually put it to use here. |
The set of expected argument names is
simply the first N variable names attached to a function’s code object:
_# In Python 3.0 (and 2.6 for compatibility):_
```
>>> def func(a, b, c, d):
... |
x = 1
... |
y = 2
...
```
`>>> code = func.__code__` _# Code object of function object_
```
>>> code.co_nlocals
6
```
`>>> code.co_varnames` _# All local var names_
```
('a', 'b', 'c', 'd', 'x', 'y')
```
`>>> code.co_varnames[:code.co_argcount]` _# First N locals are expected args_
```
('a', 'b', 'c', 'd')
```
`>>> i... |
Run a dir call on function and code objects for more
details.
###### Argument assumptions
Given this set of expected argument names, the solution relies on two constraints on
argument passing order imposed by Python (these still hold true in both 2.6 and 3.0):
- At the call, all positional arguments appear before a... |
All
“name=value” syntax must appear after any simple “name” in both places.
To simplify our work, we can also make the assumption that a call is valid in general—
i.e., that all arguments either will receive values (by name or position), or will be omitted
intentionally to pick up defaults. |
This assumption won’t necessarily hold, because the
function has not yet actually been called when the wrapper logic tests validity—the call
**|**
-----
may still fail later when invoked by the wrapper layer, due to incorrect argument passing. |
As long as that doesn’t cause the wrapper to fail any more badly, though, we can
finesse the validity of the call. |
This helps, because validating calls before they are actually made would require us to emulate Python’s argument-matching algorithm in
full—again, too complex a procedure for our tool.
###### Matching algorithm
Now, given these constraints and assumptions, we can allow for both keywords and
omitted default arguments ... |
When a call is intercepted,
we can make the following assumptions:
- All N passed positional arguments in *pargs must match the first N expected arguments obtained from the function’s code object. |
This is true per Python’s call
ordering rules, outlined earlier, since all positionals precede all keywords.
- To obtain the names of arguments actually passed by position, we can slice the list
of all expected arguments up to the length N of the *pargs positionals tuple.
- Any arguments after the first N expected ... |
Under
this scheme, the decorator will simply skip any argument to be checked that was omitted between the rightmost positional argument and the leftmost keyword argument,
between keyword arguments, or after the rightmost positional in general. |
Trace
through the decorator and its test script to see how this is realized in code.
###### Open Issues
Although our range-testing tool works as planned, two caveats remain. |
First, as mentioned earlier, calls to the original function that are not valid still fail in our final decorator. |
The following both trigger exceptions, for example:
```
omitargs()
omitargs(d=8, c=7, b=6)
```
These only fail, though, where we try to invoke the original function, at the end of the
wrapper. |
While we could try to imitate Python’s argument matching to avoid this,
**|**
-----
there’s not much reason to do so—since the call would fail at this point anyhow, we
might as well let Python’s own argument-matching logic detect the problem for us.
Lastly, although our final version handles positional arguments, ... |
We
probably don’t need to care for our purposes, though:
- If an extra keyword argument is passed, its name will show up in **kargs and can
be tested normally if mentioned to the decorator.
- If an extra keyword argument is not passed, its name won’t be in either **kargs or
the sliced expected positionals list, and... |
Because such arguments are not listed in
the function’s definition, there’s no way to map a name given to the decorator back
to an expected relative position.
In other words, as it is the code supports testing arbitrary keyword arguments by name,
but not arbitrary positionals that are unnamed and hence have no set pos... |
Since we’ve already exhausted the space allocation for
this example, though, if you care about such improvements you’ve officially crossed
over into the realm of suggested exercises.
###### Decorator Arguments Versus Function Annotations
Interestingly, the function annotation feature introduced in Python 3.0 could pr... |
We would still need a function decorator to wrap the function
in order to intercept later calls, but we would essentially trade decorator argument
syntax:
```
@rangetest(a=(1, 5), c=(0.0, 1.0))
def func(a, b, c): # func = rangetest(...)(func)
print(a + b + c)
```
**|**
-----
for annotation synta... |
The following script illustrates the structure of the resulting decorators under both schemes, in incomplete skeleton code. |
The decorator arguments code
pattern is that of our complete solution shown earlier; the annotation alternative requires one less level of nesting, because it doesn’t need to retain decorator arguments:
_# Using decorator arguments_
```
def rangetest(**argchecks):
def onDecorator(func):
def onCall(*pargs, ... |
Really,
all this buys us is a different user interface for our tool—it will still need to match
argument names against expected argument names to obtain relative positions as
before.
In fact, using annotation instead of decorator arguments in this example actually limits
_its utility. |
For one thing, annotation only works under Python 3.0, so 2.6 is no longer_
supported; function decorators with arguments, on the other hand, work in both
versions.
More importantly, by moving the validation specifications into the def header, we essentially commit the function to a single role—since annotation allows... |
For instance, we cannot
use range-test annotations for any other role.
By contrast, because decorator arguments are coded outside the function itself, they
are both easier to remove and more general—the code of the function itself does not
imply a single decoration purpose. |
In fact, by nesting decorators with arguments, we
can apply multiple augmentation steps to the same function; annotation directly supports only one. |
With decorator arguments, the function itself also retains a simpler,
normal appearance.
Still, if you have a single purpose in mind, and you can commit to supporting 3.X only,
the choice between annotation and decorator arguments is largely stylistic and subjective. |
As is so often true in life, one person’s annotation may well be another’s syntactic
clutter....
###### Other Applications: Type Testing (If You Insist!)
The coding pattern we’ve arrived at for processing arguments in decorators could be
applied in other contexts. |
Checking argument data types at development time, for example, is a straightforward extension:
```
def typetest(**argchecks):
def onDecorator(func):
....
def onCall(*pargs, **kargs):
positionals = list(allargs)[:len(pargs)]
for (argname, type) in argchecks.items():
... |
Using function annotations instead of decorator arguments
for such a decorator, as described in the prior section, would make this look even more
like type declarations in other languages:
```
@typetest
def func(a: int, b, c: float, d): # func = typetest(func)
... |
# Gasp!...
```
As you should have learned in this book, though, this particular role is generally a bad
idea in working code, and not at all Pythonic (in fact, it’s often a symptom of an
ex-C++ programmer’s first attempts to use Python).
Type testing restricts your function to work on specific types only, instead of ... |
In effect, it limits your code and
breaks its flexibility. |
On the other hand, every rule has exceptions; type checking may
come in handy in isolated cases while debugging and when interfacing with code written in more restrictive languages, such as C++. |
This general pattern of argument processing might also be applicable in a variety of less controversial roles.
###### Chapter Summary
In this chapter, we explored decorators—both the function and class varieties. |
As we
learned, decorators are a way to insert code to be run automatically when a function
or class is defined. |
When a decorator is used, Python rebinds a function or class name
to the callable object it returns. |
This hook allows us to add a layer of wrapper logic to
function calls and class instance creation calls, in order to manage functions and instances. |
As we also saw, manager functions and manual name rebinding can achieve
the same effect, but decorators provide a more explicit and uniform solution.
As we’ll see in the next chapter, class decorators can also be used to manage classes
themselves, rather than just their instances. |
Because this functionality overlaps with
metaclasses, the topic of the next chapter, you’ll have to read ahead for the rest of this
story. First, though, work through the following quiz. |
Because this chapter was mostly
**|**
-----
focused on its larger examples, its quiz will ask you to modify some of its code in order
to review.
###### Test Your Knowledge: Quiz
1. |
As mentioned in one of this chapter’s Notes, the timer function decorator with
decorator arguments that we wrote in the section “Adding Decorator Arguments” on page 1008 can be applied only to simple functions, because it uses a
nested class with a `__call__ operator overloading method to catch calls. |
This`
structure does not work for class methods because the decorator instance is passed
to `self, not the subject class instance. |
Rewrite this decorator so that it can be`
applied to both simple functions and class methods, and test it on both functions
and methods. |
(Hint: see the section “Class Blunders I: Decorating Class Methods” on page 1001 for pointers.) Note that you may make use of assigning function
object attributes to keep track of total time, since you won’t have a nested class for
state retention and can’t access nonlocals from outside the decorator code.
2. |
The Public/Private class decorators we wrote in this chapter will add overhead to
every attribute fetch in a decorated class. |
Although we could simply delete the @
decoration line to gain speed, we could also augment the decorator itself to check
the __debug__ switch and perform no wrapping at all when the –O Python flag is
passed on the command line (just as we did for the argument range-test decorators).
That way, we can speed our program w... |
Code and test this extension.
###### Test Your Knowledge: Answers
1. Here’s one way to code the first question’s solution, and its output (albeit with
class methods that run too fast to time). |
The trick lies in replacing nested classes
with nested functions, so the self argument is not the decorator’s instance, and
assigning the total time to the decorator function itself so it can be fetched later
through the original rebound name (see the section “State Information Retention
Options” on page 997 of this ch... |
The following satisfies the second question—it’s been augmented to return the
original class in optimized mode (–O), so attribute accesses don’t incur a speed hit.
Really, all I did was add the debug mode test statements and indent the class further
to the right. |
Add operator overloading method redefinitions to the wrapper class
if you want to support delegation of these to the subject class in 3.0, too (2.6 routes
these through __getattr__, but 3.0 and new-style classes in 2.6 do not).
```
traceMe = False
def trace(*args):
if traceMe: print('[' + ' '.join(map(str... |
As we
learned in the prior chapter, function and class decorators allow us to intercept and
augment function calls and class instance creation calls. |
In a similar sprit, metaclasses
allow us to intercept and augment class creation—they provide an API for inserting
extra logic to be run at the conclusion of a class statement, albeit in different ways than
decorators. |
As such, they provide a general protocol for managing class objects in a
program.
Like all the subjects dealt with in this part of the book, this is an advanced topic that
can be investigated on an as-needed basis. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.