Text stringlengths 1 9.41k |
|---|
For our example, we simply test the
attribute name to know when a managed attribute is being fetched; others are stored
physically on the instance and so never reach __getattr__. |
Although this approach is
more general than using properties or descriptors, extra work may be required to imitate
the specific-attribute focus of other tools. |
We need to check names at runtime, and we
must code a __setattr__ in order to intercept and validate attribute assignments.
As for the property and descriptor versions of this example, it’s critical to notice that
the attribute assignments inside the `__init__ constructor method trigger the class’s`
```
__setattr__ me... |
When this method assigns to self.name, for example, it au
```
tomatically invokes the __setattr__ method, which transforms the value and assigns
it to an instance attribute called name. |
By storing name on the instance, it ensures that
future accesses will not trigger __getattr__. |
In contrast, acct is stored as _acct, so that
later accesses to acct do invoke __getattr__.
In the end, this class, like the prior two, manages attributes called `name,` `age, and`
```
acct; allows the attribute addr to be accessed directly; and provides a read-only attribute
```
called remain that is entirely virtua... |
Clarity
matters more than code size, of course, but extra code can sometimes imply extra
development and maintenance work. |
Probably more important here are roles: generic
tools like __getattr__ may be better suited to generic delegation, while properties and
descriptors are more directly designed to manage specific attributes.
Also note that the code here incurs extra calls when setting unmanaged attributes (e.g.,
```
addr), although no e... |
Though this will likely result in negligible overhead for most programs,
properties and descriptors incur an extra call only when managed attributes are
accessed.
Here’s the __getattr__ version of our code:
```
class CardHolder:
acctlen = 8 # Class data
retireage = 59.5
def __init__(self,... |
Every attribute fetch is caught here, so we test the attribute
names to detect managed attributes and route all others to the superclass for normal
fetch processing. |
This version uses the same __setattr__ to catch assignments as the
prior version.
The code works very much like the `__getattr__ version, so I won’t repeat the full`
description here. |
Note, though, that because _every attribute fetch is routed to_
```
__getattribute__, we don’t need to mangle names to intercept them here (acct is stored
```
as acct). |
On the other hand, this code must take care to route nonmanaged attribute
fetches to a superclass to avoid looping.
**|**
-----
Also notice that this version incurs extra calls for both setting and fetching unmanaged
attributes (e.g., addr); if speed is paramount, this alternative may be the slowest of the
bunch. |
For comparison purposes, this version amounts to 32 lines of code, just like the
prior version:
```
class CardHolder:
acctlen = 8 # Class data
retireage = 59.5
def __init__(self, acct, name, age, addr):
self.acct = acct # Instance data
self.name = name #... |
Along the way, it compared and contrasted
these tools and presented a handful of use cases to demonstrate their behavior.
Chapter 38 continues our tool-building survey with a look at decorators—code run
automatically at function and class creation time, rather than on attribute access. |
Before
we continue, though, let’s work through a set of questions to review what we’ve covered
here.
**|**
-----
###### Test Your Knowledge: Quiz
1. |
How do __getattr__ and __getattribute__ differ?
2. How do properties and descriptors differ?
3. How are properties and decorators related?
4. |
What are the main functional differences between `__getattr__ and` `__getattri`
```
bute__ and properties and descriptors?
```
5. |
Isn’t all this feature comparison just a kind of argument?
###### Test Your Knowledge: Answers
1. |
The __getattr__ method is run for fetches of undefined attributes only—i.e., those
not present on an instance and not inherited from any of its classes. |
By contrast,
the `__getattribute__ method is called for every attribute fetch, whether the at-`
tribute is defined or not. |
Because of this, code inside a __getattr__ can freely fetch
other attributes if they are defined, whereas __getattribute__ must use special code
for all such attribute fetches to avoid looping (it must route fetches to a superclass
to skip itself).
2. |
Properties serve a specific role, while descriptors are more general. |
Properties define
get, set, and delete functions for a specific attribute; descriptors provide a class
with methods for these actions, too, but they provide extra flexibility to support
more arbitrary actions. |
In fact, properties are really a simple way to create a specific
kind of descriptor—one that runs functions on attribute accesses. |
Coding differs
too: a property is created with a built-in function, and a descriptor is coded with
a class; as such, descriptors can leverage all the usual OOP features of classes, such
as inheritance. |
Moreover, in addition to the instance’s state information, descriptors have local state of their own, so they can avoid name collisions in the instance.
3. |
Properties can be coded with decorator syntax. Because the property built-in accepts a single function argument, it can be used directly as a function decorator to
define a fetch access property. |
Due to the name rebinding behavior of decorators,
the name of the decorated function is assigned to a property whose get accessor is
set to the original function decorated (name = property(name)). |
Property setter
and deleter attributes allow us to further add set and delete accessors with decoration syntax—they set the accessor to the decorated function and return the augmented property.
**|**
-----
4. |
The __getattr__ and __getattribute__ methods are more generic: they can be used
to catch arbitrarily many attributes. |
In contrast, each property or descriptor provides access interception for only one specific attribute—we can’t catch every attribute fetch with a single property or descriptor. |
On the other hand, properties
and descriptors handle both attribute fetch and _assignment by design:_
```
__getattr__ and __getattribute__ handle fetches only; to intercept assignments
```
as well, `__setattr__ must also be coded. |
The implementation is also different:`
```
__getattr__ and __getattribute__ are operator overloading methods, whereas
```
properties and descriptors are objects manually assigned to class attributes.
5. |
No it isn’t. To quote from Python namesake Monty Python’s Flying Circus:
```
An argument is a connected series of statements intended to establish a
proposition.
No it isn't.
Yes it is! |
It's not just contradiction.
Look, if I argue with you, I must take up a contrary position.
Yes, but that's not just saying "No it isn't."
Yes it is!
No it isn't!
Yes it is!
No it isn't. |
Argument is an intellectual process. |
Contradiction is just
the automatic gainsaying of any statement the other person makes.
(short pause)
No it isn't.
It is.
Not at all.
Now look...
```
**|**
-----
-----
###### CHAPTER 38
### Decorators
In the advanced class topics chapter of this book (Chapter 31), we met static and class
m... |
We also met function decorators briefly in the prior chapter (Chapter 37), while
exploring the property built-in’s ability to serve as a decorator, and in Chapter 28 while
studying the notion of abstract superclasses.
This chapter picks up where the previous decorator coverage left off. |
Here, we’ll dig
deeper into the inner workings of decorators and study more advanced ways to code
new decorators ourselves. |
As we’ll see, many of the concepts we studied in earlier
chapters, such as state retention, show up regularly in decorators.
This is a somewhat advanced topic, and decorator construction tends to be of more
interest to tool builders than to application programmers. |
Still, given that decorators
are becoming increasingly common in popular Python frameworks, a basic understanding can help demystify their role, even if you’re just a decorator user.
Besides covering decorator construction details, this chapter serves as a more realistic
_case study of Python in action. |
Because its examples are somewhat larger than most of_
the others we’ve seen in this book, they better illustrate how code comes together into
more complete systems and tools. |
As an extra perk, much of the code we’ll write here
may be used as general-purpose tools in your day-to-day programs.
###### What’s a Decorator?
_Decoration is a way to specify management code for functions and classes. |
Decorators_
themselves take the form of callable objects (e.g., functions) that process other callable
objects. |
As we saw earlier in this book, Python decorators come in two related flavors:
- Function decorators do name rebinding at function definition time, providing a
layer of logic that can manage functions and methods, or later calls to them.
- Class decorators do name rebinding at class definition time, providing a lay... |
Such code can play a variety of roles, as described
in the following sections.
###### Managing Calls and Instances
For example, in typical use, this automatically run code may be used to augment calls
to functions and classes. |
It arranges this by installing wrapper objects to be invoked later:
- Function decorators install wrapper objects to intercept later _function calls and_
process them as needed.
- Class decorators install wrapper objects to intercept later instance creation calls
and process them as required.
Decorators achieve th... |
When later invoked, these
callables can perform tasks such as tracing and timing function calls, managing access
to class instance attributes, and so on.
###### Managing Functions and Classes
Although most examples in this chapter deal with using wrappers to intercept later
calls to functions and classes, this is not... |
Our primary focus
here, though, will be on their more commonly used call wrapper application.
- Class decorators can also be used to manage class objects directly, instead of instance creation calls—to augment a class with new methods, for example. |
Because
this role intersects strongly with that of metaclasses (indeed, both run at the end
of the class creation process), we’ll see additional use cases in the next chapter.
In other words, function decorators can be used to manage both function calls and
function objects, and class decorators can be used to manage ... |
By returning the decorated object itself instead of a wrapper, decorators become a simple post-creation step for functions and classes.
Regardless of the role they play, decorators provide a convenient and explicit way to
code tools useful both during program development and in live production systems.
###### Using a... |
As we’ve seen, Python itself comes with built-in decorators that have specialized roles—static method declaration, property creation, and more. |
In addition,
**|**
-----
many popular Python toolkits include decorators to perform tasks such as managing
database or user-interface logic. |
In such cases, we can get by without knowing how the
decorators are coded.
For more general tasks, programmers can code arbitrary decorators of their own. |
For
example, function decorators may be used to augment functions with code that adds
call tracing, performs argument validity testing during debugging, automatically acquires and releases thread locks, times calls made to function for optimization, and so
on. |
Any behavior you can imagine adding to a function call is a candidate for custom
function decorators.
On the other hand, function decorators are designed to augment only a specific function
or method call, not an entire object interface. |
Class decorators fill the latter role better—
because they can intercept instance creation calls, they can be used to implement arbitrary object interface augmentation or management tasks. |
For example, custom class
decorators can trace or validate every attribute reference made for an object. |
They can
also be used to implement proxy objects, singleton classes, and other common coding
patterns. |
In fact, we’ll find that many class decorators bear a strong resemblance to the
_delegation coding pattern we met in Chapter 30._
###### Why Decorators?
Like many advanced Python tools, decorators are never strictly required from a purely
technical perspective: their functionality can often be implemented instead usi... |
Moreover, as structuring tools, decorators
naturally foster encapsulation of code, which reduces redundancy and makes future
changes easier.
**|**
-----
Decorators do have some potential drawbacks, too—when they insert wrapper logic,
they can alter the types of the decorated objects, and they may incur extra calls. |
On the
other hand, the same considerations apply to any technique that adds wrapping logic
to objects.
We’ll explore these tradeoffs in the context of real code later in this chapter. |
Although
the choice to use decorators is still somewhat subjective, their advantages are compelling enough that they are quickly becoming best practice in the Python world. |
To help
you decide for yourself, let’s turn to the details.
###### The Basics
Let’s get started with a first-pass look at decoration behavior from a symbolic perspective. |
We’ll write real code soon, but since most of the magic of decorators boils down
to an automatic rebinding operation, it’s important to understand this mapping first.
###### Function Decorators
Function decorators have been available in Python since version 2.5. |
As we saw earlier
in this book, they are largely just syntactic sugar that runs one function through another
at the end of a def statement, and rebinds the original function name to the result.
###### Usage
A function decorator is a kind of runtime declaration about the function whose definition follows. |
The decorator is coded on a line just before the def statement that defines
a function or method, and it consists of the `@ symbol followed by a reference to a`
_metafunction—a function (or other callable object) that manages another function._
In terms of code, function decorators automatically map the following synt... |
When the function F is later called, it’s actually
calling the object returned by the decorator, which may be either another object that
implements required wrapping logic, or the original function itself.
In other words, decoration essentially maps the first of the following into the second
(though the decorator is r... |
# meth = staticmethod(meth)
class C:
@property
def name(self): ... |
# name = property(name)
```
In both cases, the method name is rebound to the result of a built-in function decorator,
at the end of the def statement. |
Calling the original name later invokes whatever object
the decorator returns.
###### Implementation
A decorator itself is a callable that returns a callable. |
That is, it returns the object to be
called later when the decorated function is invoked through its original name—either
a wrapper object to intercept later calls, or the original function augmented in some
way. |
In fact, decorators can be any type of callable and return any type of callable: any
combination of functions and classes may be used, though some are better suited to
certain contexts.
For example, to tap into the decoration protocol in order to manage a function just
after it is created, we might code a decorator of... |
# func = decorator(func)
```
Because the original decorated function is assigned back to its name, this simply adds
a post-creation step to function definition. |
Such a structure might be used to register a
function to an API, assign function attributes, and so on.
**|**
-----
In more typical use, to insert logic that intercepts later calls to a function, we might
code a decorator to return a different object than the original function:
```
def decorator(F):
```
_# Save ... |
# func = decorator(func)
```
This decorator is invoked at decoration time, and the callable it returns is invoked when
the original function name is later called. |
The decorator itself receives the decorated
function; the callable returned receives whatever arguments are later passed to the
decorated function’s name. |
This works the same for class methods: the implied instance
object simply shows up in the first argument of the returned callable.
In skeleton terms, here’s one common coding pattern that captures this idea—the decorator returns a wrapper that retains the original function in an enclosing scope:
```
def decorator(F)... |
When coded this way, each decorated function produces a new
scope to retain state.
To do the same with classes, we can overload the call operation and use instance attributes instead of enclosing scopes:
```
class decorator:
def __init__(self, func): # On @ decoration
self.func = func
def __call__(... |
# func is passed to __init__
func(6, 7) # 6, 7 are passed to __call__'s *args
```
When the name func is later called now, it really invokes the __call__ operator overloading method of the instance created by decorator; the __call__ method can then
**|**
-----
run the original func because it is stil... |
When coded
this way, each decorated function produces a new instance to retain state.
###### Supporting method decoration
One subtle point about the prior class-based coding is that while it works to intercept
simple function calls, it does not quite work when applied to class method functions:
```
class decorator:... |
# C instance not in args!_
```
class C:
@decorator
def method(self, x, y): # method = decorator(method)
```
_..._ _# Rebound to decorator instance_
When coded this way, the decorated method is rebound to an instance of the decorator
class, instead of a simple function.
The problem with this is that t... |
This makes it impossible to dispatch the call to the original
method—the decorator object retains the original method function, but it has no instance to pass to it.
To support both functions and methods, the nested function alternative works better:
```
def decorator(F): # F is func or method without ins... |
# Rebound to simple function
X = C()
X.method(6, 7) # Really calls wrapper(X, 6, 7)
```
When coded this way wrapper receives the C class instance in its first argument, so it
can dispatch to the original method and access state information.
Technically, this nested-function version works because Pytho... |
We’ll see how this subtle difference
can matter in more realistic examples later in this chapter.
Also note that nested functions are perhaps the most straightforward way to support
decoration of both functions and methods, but not necessarily the only way. |
The prior
chapter’s descriptors, for example, receive both the descriptor and subject class instance
when called. |
Though more complex, later in this chapter we’ll see how this tool can be
leveraged in this context as well.
###### Class Decorators
Function decorators proved so useful that the model was extended to allow class decoration in Python 2.6 and 3.0. |
Class decorators are strongly related to function decorators; in fact, they use the same syntax and very similar coding patterns. |
Rather than
wrapping individual functions or methods, though, class decorators are a way to manage classes, or wrap up instance construction calls with extra logic that manages or
augments instances created from a class.
###### Usage
Syntactically, class decorators appear just before `class statements (just as functi... |
In symbolic terms, assuming that
```
decorator is a one-argument function that returns a callable, the class decorator syntax:
@decorator # Decorate class
class C:
...
x = C(99) # Make an instance
```
is equivalent to the following—the class is automatically passed to the decorator function, ... |
Because a class decorator is also a _callable that returns a callable, most_
combinations of functions and classes suffice.
**|**
-----
However it’s coded, the decorator’s result is what runs when an instance is later created.
For example, to simply manage a class just after it is created, return the original class... |
# C = decorator(C)
```
To instead insert a wrapper layer that intercepts later instance creation calls, return a
different callable object:
```
def decorator(C):
```
_# Save or use class C_
_# Return a different callable: nested def, class with __call__, etc._
```
@decorator
class C: ... |
# C = decorator(C)
```
The callable returned by such a class decorator typically creates and returns a new
instance of the original class, augmented in some way to manage its interface. |
For
example, the following inserts an object that intercepts undefined attributes of a class
instance:
```
def decorator(cls): # On @ decoration
class Wrapper:
def __init__(self, *args): # On instance creation
self.wrapped = cls(*args)
def __getattr__(self, name): # On... |
When an attribute is later fetched from the instance, it
is intercepted by the wrapper’s __getattr__ and delegated to the embedded instance
of the original class. |
Moreover, each decorated class creates a new scope, which remembers the original class. |
We’ll flesh out this example into some more useful code
later in this chapter.
**|**
-----
Like function decorators, class decorators are commonly coded as either “factory”
functions that create and return callables, classes that use __init__ or __call__ methods
to intercept call operations, or some combination the... |
Factory functions typically
retain state in enclosing scope references, and classes in attributes.
###### Supporting multiple instances
As with function decorators, with class decorators some callable type combinations
work better than others. |
Consider the following invalid alternative to the class decorator of the prior example:
```
class Decorator:
def __init__(self, C): # On @ decoration
self.C = C
def __call__(self, *args): # On instance creation
self.wrapped = self.C(*args)
return self
def __getattr__(self... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.