Text stringlengths 1 9.41k |
|---|
In contrast, by intercepting
instance creation calls, the class decorator here allows us to trace an entire object
interface—i.e., accesses to any of its attributes.
**|**
-----
The following is the output produced by this code under both 2.6 and 3.0: attribute
fetches on instances of both the Spam and Person class... |
Just like in the original
example in Chapter 30, we can also use the decorator to wrap up a built-in type such
as a list, as long as we either subclass to allow decoration syntax or perform the decoration manually—decorator syntax requires a class statement for the @ line.
In the following, x is really a Wrapper again... |
class MyList(list): pass` _# MyList = Tracer(MyList)_
`>>> x = MyList([1, 2, 3])` _# Triggers Wrapper()_
`>>> x.append(4)` _# Triggers __getattr__, append_
```
Trace: append
>>> x.wrapped
[1, 2, 3, 4]
```
`>>> WrapList = Tracer(list)` _# Or perform decoration manually_
`>>> x = WrapList([4, 5, 6])` _# Else subc... |
Although this seems like a minor
difference, it lets us retain normal instance creation syntax and realize all the benefits
**|**
-----
of decorators in general. |
Rather than requiring all instance creation calls to route objects
through a wrapper manually, we need only augment classes with decorator syntax:
```
@Tracer # Decorator approach
class Person: ...
bob = Person('Bob', 40, 50)
sue = Person('Sue', rate=100, hours=60)
class Person: ... |
# Non-decorator approach
bob = Wrapper(Person('Bob', 40, 50))
sue = Wrapper(Person('Sue', rate=100, hours=60))
```
Assuming you will make more than one instance of a class, decorators will generally
be a net win in terms of both code size and code maintenance.
_Attribute version skew note: As we learned in Chapte... |
New-`
style classes look up such methods in _classes and skip the normal_
instance lookup entirely.
Here, this means that the __getattr__-based tracing wrapper will automatically trace and propagate operator overloading calls in 2.6, but not
in 3.0. |
To see this, display “x” directly at the end of the preceding interactive session—in 2.6 the attribute `__repr__ is traced and the list`
prints as expected, but in 3.0 no trace occurs and the list prints using a
default display for the Wrapper class:
```
>>> x # 2.6
Trace: __repr__
... |
Only simple named attributes will
work the same in both versions. |
We’ll see this version skew at work
again in a Private decorator later in this chapter.
###### Class Blunders II: Retaining Multiple Instances
Curiously, the decorator function in this example can almost be coded as a class instead
of a function, with the proper operator overloading protocol. |
The following slightly
simplified alternative works similarly because its __init__ is triggered when the @ decorator is applied to the class, and its __call__ is triggered when a subject class instance
**|**
-----
is created. |
Our objects are really instances of Tracer this time, and we essentially just
trade an enclosing scope reference for an instance attribute here:
```
class Tracer:
def __init__(self, aClass): # On @decorator
self.aClass = aClass # Use instance attribute
def __call__(self, *args): # ... |
The
net effect is that Tracer saves just one instance—the last one created. |
Experiment with
this yourself to see how, but here’s an example of the problem:
```
@Tracer
class Person: # Person = Tracer(Person)
def __init__(self, name): # Wrapper bound to Person
self.name = name
bob = Person('Bob') # bob is really a Wrapper
print(bob.name) ... |
The solution, as
in our prior class blunder for decorating methods, lies in abandoning class-based
decorators.
**|**
-----
The earlier function-based Tracer version does work for multiple instances, because
each instance construction call makes a new Wrapper instance, instead of overwriting
the state of a single sh... |
Decorators are not only arguably
magical, they can also be incredibly subtle!
###### Decorators Versus Manager Functions
Regardless of such subtleties, the Tracer class decorator example ultimately still relies
on __getattr__ to intercept fetches on a wrapped and embedded instance object. |
As
we saw earlier, all we’ve really accomplished is moving the instance creation call inside
a class, instead of passing the instance into a manager function. |
With the original nondecorator tracing example, we would simply code instance creation differently:
```
class Spam: # Non-decorator version
... |
# Any class will do
food = Wrapper(Spam()) # Special creation syntax
@Tracer
class Spam: # Decorator version
... |
# Requires @ syntax at class
food = Spam() # Normal creation syntax
```
Essentially, class decorators shift special syntax requirements from the instance creation
call to the class statement itself. |
This is also true for the singleton example earlier in
this section—rather than decorating a class and using normal instance creation calls,
we could simply pass the class and its construction arguments into a manager function:
```
instances = {}
def getInstance(aClass, *args):
if aClass not in instances:
... |
# def tracer(func, args): ... func(*args)
result = tracer(func, (1, 2)) # Special call syntax
@tracer
def func(x, y): # Decorator version
... |
# Rebinds name: func = tracer(func)
result = func(1, 2) # Normal call syntax
```
Manager function approaches like this place the burden of using special syntax on
_calls, instead of expecting decoration syntax at function and class definitions._
###### Why Decorators? |
(Revisited)
So why did I just show you ways to not use decorators to implement singletons? As I
mentioned at the start of this chapter, decorators present us with tradeoffs. |
Although
syntax matters, we all too often forget to ask the “why” questions when confronted
with new tools. |
Now that we’ve seen how decorators actually work, let’s step back for
a minute to glimpse the big picture here.
Like most language features, decorators have both pros and cons. |
For example, in the
negatives column, class decorators suffer from two potential drawbacks:
_Type changes_
As we’ve seen, when wrappers are inserted, a decorated function or class does not
retain its _original type—its name is rebound to a wrapper object, which might_
matter in programs that use object names or test o... |
In the singleton
example, both the decorator and manager function approaches retain the original
class type for instances; in the tracer code, neither approach does, because wrappers are required.
_Extra calls_
A wrapping layer added by decoration incurs the additional performance cost of
an extra call each time the de... |
In the
tracer code, both approaches require each attribute to be routed through a wrapper
layer; the singleton example avoids extra calls by retaining the original class type.
Similar concerns apply with function decorators: both decoration and manager functions incur extra calls, and type changes generally occur when... |
For most programs, the type difference
issue is unlikely to matter and the speed hit of the extra calls will be insignificant;
furthermore, the latter occurs only when wrappers are used, can often be negated by
simply removing the decorator when optimal performance is required, and is also incurred by nondecorator solu... |
Compared to the manager (a.k.a. “helper”) function solutions of the prior section, decorators offer:
_Explicit syntax_
Decorators make augmentation explicit and obvious. |
Their @ syntax is easier to
recognize than special code in calls that may appear anywhere in a source file—in
our singleton and tracer examples, for instance, the decorator lines seem more
likely to be noticed than extra code at calls would be. |
Moreover, decorators allow
function and instance creation calls to use normal syntax familiar to all Python
programmers.
_Code maintenance_
Decorators avoid repeated augmentation code at each function or class call. |
Because they appear just once, at the definition of the class or function itself, they
obviate redundancy and simplify future code maintenance. |
For our singleton and
tracer cases, we need to use special code at each call to use a manager function
approach—extra work is required both initially and for any modifications that
must be made in the future.
_Consistency_
Decorators make it less likely that a programmer will forget to use required wrapping logic. |
This derives mostly from the two prior advantages—because decoration
is explicit and appears only once, at the decorated objects themselves, decorators
promote more consistent and uniform API usage than special code that must be
included at each call. |
In the singleton example, for instance, it would be easy to
forget to route all class creation calls through special code, which would subvert
the singleton management altogether.
Decorators also promote code encapsulation to reduce redundancy and minimize future
maintenance effort; although other code structuring too... |
That said, most programmers find
them to be a net win, especially as a tool for using libraries and APIs correctly.
I can recall similar arguments being made both for and against constructor functions
in classes—prior to the introduction of __init__ methods, the same effect was often
achieved by running an instance th... |
Over time, though, despite being fundamentally a stylistic choice,
```
the __init__ syntax came to be universally preferred because it was more explicit, consistent, and maintainable. |
Although you should be the judge, decorators seem to bring
many of the same assets to the table.
**|**
-----
###### Managing Functions and Classes Directly
Most of our examples in this chapter have been designed to intercept function and
instance creation calls. |
Although this is typical for decorators, they are not limited to
this role. |
Because decorators work by running new functions and classes through decorator code, they can also be used to manage function and class objects themselves,
not just later calls made to them.
Imagine, for example, that you require methods or classes used by an application to be
registered to an API for later processing... |
Although you could provide a registration function to be called
manually after the objects are defined, decorators make your intent more explicit.
The following simple implementation of this idea defines a decorator that can be applied to both functions and classes, to add the object to a dictionary-based registry.
Be... |
In fact, our objects can be run both manually and from inside the
registry table:
```
Registry:
Eggs => <class '__main__.Eggs'> <class 'type'>
ham => <function ham at 0x02CFB738> <class 'function'>
spam => <function spam at 0x02CFB6F0> <class 'function'>
Manual calls:
4
8
16
Registry calls:
Eggs => ... |
Handlers might be registered by function or class name, as done here, or
decorator arguments could be used to specify the subject event; an extra def statement
enclosing our decorator could be used to retain such arguments for use on decoration.
This example is artificial, but its technique is very general. |
For example, function decorators might also be used to process function attributes, and class decorators might
insert new class attributes, or even new methods, dynamically. |
Consider the following
function decorators—they assign function attributes to record information for later use
by an API, but they do not insert a wrapper layer to intercept later calls:
_# Augmenting decorated objects directly_
```
>>> def decorate(func):
```
`... |
func.marked = True` _# Assign function attribute for later use_
```
... return func
...
>>> @decorate
... def spam(a, b):
... |
return a + b
...
>>> spam.marked
True
```
`>>> def annotate(text):` _# Same, but value is decorator argument_
```
... def decorate(func):
... func.label = text
... return func
... |
return decorate
...
>>> @annotate('spam data')
```
`... def spam(a, b):` _# spam = annotate(...)(spam)_
```
... |
return a + b
...
```
**|**
-----
```
>>> spam(1, 2), spam.label
(3, 'spam data')
```
Such decorators augment functions and classes directly, without catching later calls to
them. |
We’ll see more examples of class decorations managing classes directly in the
next chapter, because this turns out to encroach on the domain of metaclasses; for the
remainder of this chapter, let’s turn to two larger case studies of decorators at work.
###### Example: “Private” and “Public” Attributes
The final two s... |
Both
are presented with minimal description, partly because this chapter has exceeded its
size limits, but mostly because you should already understand decorator basics well
enough to study these on your own. |
Being general-purpose tools, these examples give
us a chance to see how decorator concepts come together in more useful code.
###### Implementing Private Attributes
The following class decorator implements a Private declaration for class instance attributes—that is, attributes stored on an instance, or inherited from... |
It’s not
exactly C++ or Java, but it provides similar access control as an option in Python.
We saw an incomplete first-cut implementation of instance attribute privacy for
changes only in Chapter 29. |
The version here extends this concept to validate attribute
fetches too, and it uses delegation instead of inheritance to implement the model. |
In
fact, in a sense this is just an extension to the attribute tracer class decorator we met
earlier.
Although this example utilizes the new syntactic sugar of class decorators to code attribute privacy, its attribute interception is ultimately still based upon the
```
__getattr__ and __setattr__ operator overloading ... |
It will work under both
Python 2.6 and 3.0 because it employs 3.0 print and raise syntax, though it catches
operator overloading method attributes in 2.6 only (more on this in a moment):
```
"""
Privacy for attributes fetched from class instances.
See self-test code at end of file for a usage example.
Decorator... |
To help you study, though, here are a few highlights worth
mentioning.
###### Inheritance versus delegation
The first-cut privacy example shown in Chapter 29 used _inheritance to mix in a_
```
__setattr__ to catch accesses. |
Inheritance makes this difficult, however, because dif
```
ferentiating between accesses from inside or outside the class is not straightforward
(inside access should be allowed to run normally, and outside access should be restricted). |
To work around this, the Chapter 29 example requires inheriting classes to use
```
__dict__ assignments to set attributes—an incomplete solution at best.
```
The version here uses delegation (embedding one object inside another) instead of inheritance; this pattern is better suited to our task, as it makes it much eas... |
Attribute accesses from
**|**
-----
outside the subject class are intercepted by the wrapper layer’s overloading methods
and delegated to the class if valid; accesses inside the class itself (i.e., through `self`
inside its methods’ code) are not intercepted and are allowed to run normally without
checks, because p... |
What really happens, though, is that the arguments are passed
to the Private function, and Private returns the decorator function to be applied to the
subject class. |
That is, the arguments are used before decoration ever occurs; Private
returns the decorator, which in turn “remembers” the privates list as an enclosing scope
reference.
###### State retention and enclosing scopes
Speaking of enclosing scopes, there are actually three levels of state retention at work
in this code:
... |
As we learned in the prior
chapter, it cannot assign an attribute directly without looping. However, it uses the
```
setattr built-in instead of __dict__ to set attributes in the wrapped object itself. |
More
```
over, getattr is used to fetch attributes in the wrapped object, since they may be stored
in the object itself or inherited by it.
Because of that, this code will work for most classes. |
You may recall from Chapter 31
that new-style classes with __slots__ may not store attributes in a __dict__. |
However,
because we only rely on a __dict__ at the onInstance level here, not in the wrapped
instance, and because `setattr and` `getattr apply to attributes based on both`
```
__dict__ and __slots__, our decorator applies to classes using either storage scheme.
###### Generalizing for Public Declarations, Too
```
No... |
The example listed in this section allows
**|**
-----
a class to use decorators to define a set of either Private or Public instance attributes
(attributes stored on an instance or inherited from its classes), with the following
semantics:
- Private declares attributes of a class’s instances that cannot be fetche... |
That is, any name declared
```
Private cannot be accessed from outside the class, while any name not declared
Private can be freely fetched or assigned from outside the class.
```
- Public declares attributes of a class’s instances that can be fetched or assigned from
both outside the class and within the class’s... |
That is, any name declared
```
Public can be freely accessed anywhere, while any name not declared Public cannot
```
be accessed from outside the class.
```
Private and Public declarations are intended to be mutually exclusive: when using
Private, all undeclared names are considered Public, and when using Public, al... |
They are essentially inverses, though unde-`
clared names not created by class methods behave slightly differently—they can be
assigned and thus created outside the class under Private (all undeclared names are
accessible), but not under Public (all undeclared names are inaccessible).
Again, study this code on your ow... |
Notice that this
scheme adds an additional fourth level of state retention at the top, beyond that described in the preceding section: the test functions used by the lambdas are saved in an extra
enclosing scope. |
This example is coded to run under either Python 2.6 or 3.0, though
it comes with a caveat when run under 3.0 (explained briefly in the file’s docstring and
expanded on after the code):
```
"""
Class decorator with Private and Public attribute declarations.
Controls access to attributes stored on an instance, or ... |
Private declares attribute names that
cannot be fetched or assigned outside the decorated class, and
Public declares all the names that can. |
Caveat: this works in
3.0 for normally named attributes only: __X__ operator overloading
methods implicitly run for built-in operations do not trigger
either __getattr__ or __getattribute__ in new-style classes.
Add __X__ methods here to intercept and delegate built-ins.
"""
traceMe = False
def trace(*arg... |
Here’s a quick look at these
class decorators in action at the interactive prompt (they work the same in 2.6 and 3.0);
as advertised, non-Private or Public names can be fetched and changed from outside
the subject class, but Private or non-Public names cannot:
```
>>> from access import Private, Public
```
`>>> @Pri... |
class Person:` _# Person = onInstance with state_
```
... def __init__(self, name, age):
... self.name = name
```
`... |
self.age = age` _# Inside accesses run normally_
```
...
>>> X = Person('Bob', 40)
```
`>>> X.name` _# Outside accesses validated_
```
'Bob'
>>> X.name = 'Sue'
>>> X.name
'Sue'
>>> X.age
TypeError: private attribute fetch: age
>>> X.age = 'Tom'
TypeError: private attribute change: age
>>> @Public... |
class Person:
... def __init__(self, name, age):
... self.name = name
... |
self.age = age
...
```
`>>> X = Person('bob', 40)` _# X is an onInstance_
`>>> X.name` _# onInstance embeds Person_
```
'bob'
>>> X.name = 'Sue'
```
**|**
-----
```
>>> X.name
'Sue'
>>> X.age
TypeError: private attribute fetch: age
>>> X.age = 'Tom'
TypeError: private attribute change: age
#####... |
Since this is
just a generalization of the preceding section’s example, most of the notes there apply
here as well.
###### Using __X pseudoprivate names
Besides generalizing, this version also makes use of Python’s __X pseudoprivate name
mangling feature (which we met in Chapter 30) to localize the wrapped attribute ... |
This avoids the prior
version’s risk for collisions with a wrapped attribute that may be used by the real, wrapped class, and it’s useful in a general tool like this. |
It’s not quite “privacy,” though,
because the mangled name can be used freely outside the class. |
Notice that we also
have to use the fully expanded name string ('_onInstance__wrapped') in __setattr__,
because that’s what Python changes it to.
###### Breaking privacy
Although this example does implement access controls for attributes of an instance and
its classes, it is possible to subvert these controls in vari... |
If you have to
explicitly try to do so, though, these controls are probably sufficient for normal
intended use. |
Of course, privacy controls can generally be subverted in any language
if you try hard enough (#define private public may work in some C++ implementations, too). |
Although access controls can reduce accidental changes, much of this is up
to programmers in any language; whenever source code may be changed, access control
will always be a bit of a pipe dream.
###### Decorator tradeoffs
We could again achieve the same results without decorators, by using manager functions or codi... |
The chief potential
downsides of this and any other wrapper-based approach are that attribute access incurs an extra call, and instances of decorated classes are not really instances of the
original decorated class—if you test their type with X.__class__ or isinstance(X, C),
**|**
-----
for example, you’ll find tha... |
Unless you plan
to do introspection on objects’ types, though, the type issue is probably irrelevant.
###### Open Issues
As is, this example works as planned under Python 2.6 and 3.0 (provided operator
overloading methods to be delegated are redefined in the wrapper). |
As with most software, though, there is always room for improvement.
###### Caveat: operator overloading methods fail to delegate under 3.0
Like all delegation-based classes that use `__getattr__, this decorator works cross-`
version for normally named attributes only; operator overloading methods like
```
__str__ an... |
Hence, the __X__ operator overloading
methods implicitly run for built-in operations do _not trigger either_ `__getattr__ or`
```
__getattribute__ in new-style classes in 2.6 and all classes in 3.0; such attribute fetches
```
skip our onInstance.__getattr__ altogether, so they cannot be validated or delegated.
Our de... |
Since all classes are new-style
automatically in 3.0, though, such methods will fail if they are coded on the embedded
object. |
The simplest workaround in 3.0 is to redefine redundantly in onInstance all the
operator overloading methods that can possibly be used in wrapped objects. |
Such extra
methods can be added by hand, by tools that partly automate the task (e.g., with class
decorators or the metaclasses discussed in the next chapter), or by definition in
superclasses.
To see the difference yourself, try applying the decorator to a class that uses operator
overloading methods under 2.6; valid... |
class Person:
... def __init__(self):
... self.age = 42
... def __str__(self):
... return 'Person: ' + str(self.age)
... def __add__(self, yrs):
... |
self.age += yrs
...
```
**|**
-----
```
>>> X = Person()
```
`>>> X.age` _# Name validations fail correctly_
```
TypeError: private attribute fetch: age
```
`>>> print(X)` _# __getattr__ => runs Person.__str___
```
Person: 42
```
`>>> X + 10` _# __getattr__ => runs Person.__add___
`>>> print(X)` _# __get... |
class Person:
... def __init__(self):
... self.age = 42
... def __str__(self):
... return 'Person: ' + str(self.age)
... def __add__(self, yrs):
... |
self.age += yrs
...
```
`>>> X = Person()` _# Name validations still work_
`>>> X.age` _# But 3.0 fails to delegate built-ins!_
```
TypeError: private attribute fetch: age
>>> print(X)
<access.onInstance object at 0x025E0790>
>>> X + 10
TypeError: unsupported operand type(s) for +: 'onInstance' and 'int'
... |
Python’s property feature, which we met in Chapter 37, won’t help here
either; recall that properties are automatically run code associated with _specific_
attributes defined when a class is written, and are not designed to handle arbitrary
attributes in wrapped objects.
As mentioned earlier, the most straightforward ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.