Text stringlengths 1 9.41k |
|---|
In practice,
descriptors can also be used to compute attribute values each time they are fetched.
The following illustrates—it’s a rehash of the same example we coded for properties,
which uses a descriptor to automatically square an attribute’s value each time it is
fetched:
```
class DescSquare:
def __init__(se... |
In fact, descriptors can use both instance state and descriptor state, or any combination thereof:
- Descriptor state is used to manage data internal to the workings of the descriptor.
- Instance state records information related to and possibly created by the client
class.
Descriptor methods may use either, but d... |
For example, the following descriptor attaches information to its own
instance, so it doesn’t clash with that on the client class’s instance:
```
class DescState: # Use descriptor state
def __init__(self, value):
self.value = value
def __get__(self, instance, owner): # On attr fetch
... |
Notice that only the descriptor attribute
is managed here—get and set accesses to X are intercepted, but accesses to Y and Z are
not (Y is attached to the client class and Z to the instance). |
When this code is run, X is
computed when fetched:
```
DescState get
20 3 4
DescState set
DescState get
50 6 7
```
It’s also feasible for a descriptor to store or use an attribute attached to the client class’s
instance, instead of itself. |
The descriptor in the following example assumes the instance
has an attribute _Y attached by the client class, and uses it to compute the value of the
attribute it represents:
```
class InstState: # Using instance state
def __get__(self, instance, owner):
print('InstState get') # Assume s... |
The new descriptor here has no information itself, but it uses an attribute assumed to exist in the instance—that attribute
is named _Y, to avoid collisions with the name of the descriptor itself. |
When this version
is run the results are similar, but a second attribute is managed, using state that lives
in the instance instead of the descriptor:
```
DescState get
InstState get
20 300 4
DescState set
InstState set
DescState get
InstState get
50 600 7
```
Both descriptor and instance state have ro... |
In fact, this is a general advantage that
descriptors have over properties—because they have state of their own, they can easily
retain data internally, without adding it to the namespace of the client instance object.
###### How Properties and Descriptors Relate
As mentioned earlier, properties and descriptors are s... |
Now that you know how both
work, you should also be able to see that it’s possible to simulate the property built-in
with a descriptor class like the following:
```
class Property:
def __init__(self, fget=None, fset=None, fdel=None, doc=None):
self.fget = fget
self.fset = fset
self.fdel = fdel ... |
Attribute fetches, for example, are routed from the `Person class, to the`
```
Property class’s __get__ method, and back to the Person class’s getName. |
With descrip
```
tors, this “just works.”
Note that this descriptor class equivalent only handles basic property usage, though;
to use @ _decorator syntax to also specify set and delete operations, our Property class_
would also have to be extended with setter and deleter methods, which would save
the decorated access... |
See Chapter 31 for more on slots.
In Chapter 38, we’ll also make use of descriptors to implement function
decorators that apply to both functions and methods. |
As you’ll see there,
because descriptors receive both descriptor and subject class instances
they work well in this role, though nested functions are usually a simpler
solution.
###### __getattr__ and __getattribute__
So far, we’ve studied properties and descriptors—tools for managing specific attributes.
The `__geta... |
Like properties and descriptors, they allow us to insert code to be run automatically when attributes are accessed; as we’ll see, though, these two methods can be used in more general ways.
Attribute fetch interception comes in two flavors, coded with two different methods:
- __getattr__ is run for undefined attribu... |
The
latter of these is available for new-style classes in 2.6, and for all (implicitly new-style)
classes in 3.0. |
These two methods are representatives of a set of attribute interception
methods that also includes __setattr__ and __delattr__. |
Because these methods have
similar roles, we will generally treat them as a single topic here.
**|**
-----
Unlike properties and descriptors, these methods are part of Python’s operator over_loading protocol—specially named methods of a class, inherited by subclasses, and run_
automatically when instances are used ... |
Like all methods of a class, they each receive a first self argument when called, giving access to any
required instance state information or other methods of the class.
The __getattr__ and __getattribute__ methods are also more generic than properties
and descriptors—they can be used to intercept access to any (or ev... |
Because of this,
these two methods are well suited to general delegation-based coding patterns—they
can be used to implement wrapper objects that manage all attribute accesses for an
embedded object. |
By contrast, we must define one property or descriptor for every
attribute we wish to intercept.
Finally, these two methods are more narrowly focused than the alternatives we considered earlier: they intercept attribute fetches only, not assignments. |
To also catch attribute changes by assignment, we must code a `__setattr__ method—an operator`
overloading method run for every attribute fetch, which must take care to avoid recursive loops by routing attribute assignments through the instance namespace dictionary.
Although much less common, we can also code a `__del... |
By contrast, properties and descriptors catch get, set, and delete operations by design.
Most of these operator overloading methods were introduced earlier in the book; here,
we’ll expand on their usage and study their roles in larger contexts.
###### The Basics
`__getattr__ and` `__setattr__ were introduced in Chap... |
In short, if a class defines or
```
inherits the following methods, they will be run automatically when an instance is used
in the context described by the comments to the right:
```
def __getattr__(self, name): # On undefined attribute fetch [obj.name]
def __getattribute__(self, name): # On all attribute fetc... |
The
two get methods normally return an attribute’s value, and the other two return nothing
(None). |
For example, to catch every attribute fetch, we can use either of the first two
methods above, and to catch every attribute assignment we can use the third:
```
class Catcher:
def __getattr__(self, name):
print('Get:', name)
def __setattr__(self, name, value):
```
**|**
-----
```
print('Set:',... |
Because all attribute are routed to our interception methods
generically, we can validate and pass them along to embedded, managed objects. |
The
following class (borrowed from Chapter 30), for example, traces every attribute fetch
made to another object passed to the wrapper class:
```
class Wrapper:
def __init__(self, object):
self.wrapped = object # Save object
def __getattr__(self, attrname):
print('Trace:', attrname) ... |
recursing). Because_ `__getattr__ is called for undefined`
attributes only, it can freely fetch other attributes within its own code. |
However, because __getattribute__ and __setattr__ are run for all attributes, their code needs to
be careful when accessing other attributes to avoid calling themselves again and triggering a recursive loop.
For example, another attribute fetch run inside a __getattribute__ method’s code will
trigger __getattribute__ ... |
This avoids direct attribute assignment:
**|**
-----
```
def __setattr__(self, name, value):
self.__dict__['other'] = value # Use atttr dict to avoid me
```
Although it’s a less common approach, `__setattr__ can also pass its own attribute`
assignments to a higher superclass to avoid looping, just... |
Strange but true!
The __delattr__ method is rarely used in practice, but when it is, it is called for every
attribute deletion (just as __setattr__ is called for every attribute assignment). |
Therefore, you must take care to avoid loops when deleting attributes, by using the same
techniques: namespace dictionaries or superclass method calls.
###### A First Example
All this is not nearly as complicated as the prior section may have implied. |
To see how
to put these ideas to work, here is the same first example we used for properties and
descriptors in action again, this time implemented with attribute operator overloading
methods. |
Because these methods are so generic, we test attribute names here to know
when a managed attribute is being accessed; others are allowed to pass normally:
```
class Person:
def __init__(self, name): # On [Person()]
self._name = name # Triggers __setattr__!
def __getattr__(self, attr): ... |
Because they are generic,
```
__getattr__ and __getattribute__ are probably more commonly used in delegation
```
base code (as sketched earlier), where attribute access is validated and routed to an
embedded object. |
Where just a single attribute must be managed, properties and descriptors might do as well or better.
**|**
-----
###### Computed Attributes
As before, our prior example doesn’t really do anything but trace attribute fetches; it’s
not much more work to compute an attribute’s value when fetched. |
As for properties
and descriptors, the following creates a virtual attribute X that runs a calculation when
fetched:
```
class AttrSquare:
def __init__(self, start):
self.value = start # Triggers __setattr__!
def __getattr__(self, attr): # On undefined attr fetch
if attr == ... |
Notice the implicit routing
going on in inside this class’s methods:
- self.value=start inside the constructor triggers __setattr__
- self.value inside __getattribute__ triggers __getattribute__ again
In fact, __getattribute__ is run twice each time we fetch attribute X. |
This doesn’t happen in the __getattr__ version, because the value attribute is not undefined. |
If you care
about speed and want to avoid this, change __getattribute__ to use the superclass to
fetch value as well:
```
def __getattribute__(self, attr):
if attr == 'X':
return object.__getattribute__(self, 'value') ** 2
```
Of course, this still incurs a call to the superclass method, but not an a... |
Add print calls to these methods to trace how and when
they run.
###### __getattr__ and __getattribute__ Compared
To summarize the coding differences between __getattr__ and __getattribute__, the
following example uses both to implement three attributes—attr1 is a class attribute,
```
attr2 is an instance attribute, ... |
The __getattribute__ version, on the other hand, intercepts all attribute fetches
and must route those it does not manage to the superclass fetcher to avoid loops:
```
1
2
get: attr3
3
--------------------------------------- get: attr1
1
get: attr2
2
get: attr3
3
```
Although __getattribute__ can ... |
The following version uses properties to intercept and calculate attributes named square and cube. |
Notice how their
base values are stored in names that begin with an underscore, so they don’t clash with
the names of the properties themselves:
_# 2 dynamically computed attributes with properties_
```
class Powers:
def __init__(self, square, cube):
self._square = square # _square is the base va... |
Note
that these descriptors store base values as instance state, so they must use leading underscores again so as not to clash with the names of descriptors (as we’ll see in the final
example of this chapter, we could avoid this renaming requirement by storing base
values as descriptor state instead):
_# Same, but wit... |
First, though, we need to study a
pitfall associated with two of these tools.
**|**
-----
###### Intercepting Built-in Operation Attributes
When I introduced __getattr__ and __getattribute__, I stated that they intercept undefined and all attribute fetches, respectively, which makes them ideal for delegationbased ... |
While this is true for normally named attributes, their behavior
needs some additional clarification: for method-name attributes implicitly fetched by
built-in operations, these methods may _not be run at all. |
This means that operator_
overloading method calls cannot be delegated to wrapped objects unless wrapper
classes somehow redefine these methods themselves.
For example, attribute fetches for the __str__, __add__, and __getitem__ methods run
implicitly by printing, + expressions, and indexing, respectively, are not rou... |
Specifically:
- In Python 3.0, neither `__getattr__ nor __getattribute__ is run for such attributes.`
- In Python 2.6, __getattr__ _is run for such attributes if they are undefined in the_
class.
- In Python 2.6, __getattribute__ is available for new-style classes only and works
as it does in 3.0.
In other words... |
In Python 2.X,
the methods such operations invoke are looked up at runtime in instances, like all other
attributes; in Python 3.0 such methods are looked up in classes instead.
This change makes delegation-based coding patterns more complex in 3.0, since they
cannot generically intercept operator overloading method ca... |
This is not a showstopper—wrapper classes can work around this
constraint by redefining all relevant operator overloading methods in the wrapper itself,
in order to delegate calls. |
These extra methods can be added either manually, with
tools, or by definition in and inheritance from common superclasses. |
This does, however, make wrappers more work than they used to be when operator overloading
methods are a part of a wrapped object’s interface.
Keep in mind that this issue applies only to __getattr__ and __getattribute__. |
Because
properties and descriptors are defined for specific attributes only, they don’t really
apply to delegation-based classes at all—a single property or descriptor cannot be used
to intercept arbitrary attributes. |
Moreover, a class that defines both operator overloading methods and attribute interception will work correctly, regardless of the type of
attribute interception defined. |
Our concern here is only with classes that do not have
operator overloading methods defined, but try to intercept them generically.
Consider the following example, the file _getattr.py, which tests various attribute_
types and built-in operations on instances of classes containing `__getattr__ and`
```
__getattribute_... |
(implicit via built-in)
except:
print('fail ()')
X.__call__() # __call__? (explicit, not inherited)
print(X.__str__()) # __str__? |
(explicit, inherited from type)
print(X) # __str__? |
(implicit via built-in)
```
**|**
-----
When run under Python 2.6, __getattr__ _does receive a variety of implicit attribute_
fetches for built-in operations, because Python looks up such attributes in instances
normally. |
Conversely, __getattribute__ is not run for any of the operator overloading
names, because such names are looked up in classes only:
```
C:\misc> c:\python26\python getattr.py
GetAttr===========================================
getattr: other
__len__: 42
getattr: __getitem__
getattr: __coerce__
getattr: __... |
By contrast, __getattribute__ fails to catch implicit fetches of either
```
attribute name for built-in operations.
Really, the __getattribute__ case is the same in 2.6 as it is in 3.0, because in 2.6 classes
must be made new-style by deriving from `object to use this method. |
This code’s`
```
object derivation is optional in 3.0 because all classes are new-style.
```
When run under Python 3.0, though, results for __getattr__ differ—none of the implicitly run operator overloading methods trigger either attribute interception method
when their attributes are fetched by built-in operations. |
Python 3.0 skips the normal
instance lookup mechanism when resolving such names:
```
C:\misc> c:\python30\python getattr.py
GetAttr===========================================
getattr: other
__len__: 42
fail []
fail +
fail ()
```
**|**
-----
```
getattr: __call__
<__main__.GetAttr object at 0x025D1... |
In general
delegation tools, this can add many extra methods.
Of course, the addition of such methods can be partly automated by tools that augment
classes with new methods (the class decorators and metaclasses of the next two chapters
might help here). |
Moreover, a superclass might be able to define all these extra methods
once, for inheritance in delegation-based classes. |
Still, delegation coding patterns require extra work in 3.0.
For a more realistic illustration of this phenomenon as well as its workaround, see the
```
Private decorator example in the following chapter. |
There, we’ll see that it’s also
```
**|**
-----
possible to insert a __getattribute__ in the client class to retain its original type, although this method still won’t be called for operator overloading methods; printing
still runs a __str__ defined in such a class directly, for example, instead of routing the
requ... |
Now that
you understand how attribute interception works, I’ll be able to explain one of its
stranger bits.
For an example of this 3.0 change at work in Python itself, see the discussion of the 3.0 os.popen object in Chapter 14. |
Because it is implemented with a wrapper that uses `__getattr__ to delegate attribute`
fetches to an embedded object, it does not intercept the next(X) builtin iterator function in Python 3.0, which is defined to run __next__. |
It
does, however, intercept and delegate explicit `X.__next__() calls, be-`
cause these are not routed through the built-in and are not inherited
from a superclass like __str__ is.
This is equivalent to __call__ in our example—implicit calls for builtins do not trigger __getattr__, but explicit calls to names not inhe... |
In other words, this change impacts not only our
delegators, but also those in the Python standard library! |
Given the
scope of this change, it’s possible that this behavior may evolve in the
future, so be sure to verify this issue in later releases.
###### Delegation-Based Managers Revisited
The object-oriented tutorial of Chapter 27 presented a Manager class that used object
embedding and method delegation to customize it... |
Here
is the script’s output—Sue receives a 10% raise from Person, but Tom gets 20% because
```
giveRaise is customized in Manager:
C:\misc> c:\python30\python getattr.py
Jones
[Person: Sue Jones, 110000]
Jones
[Person: Tom Jones, 60000]
```
By contrast, though, notice what occurs when we print a Manager at t... |
With that in mind, watch what happens if we` _delete the_ `Manager.__str__`
method in this code:
_# Delete the Manager __str__ method_
```
class Manager:
def __init__(self, name, pay):
self.person = Person(name, 'mgr', pay) # Embed a Person object
def giveRaise(self, percent, bonus=.10):
self.p... |
Instead, a default __str__ display method
inherited from the class’s implicit object superclass is looked up and run (sue still prints
correctly, because Person has an explicit __str__):
```
C:\misc> c:\python30\python person.py
Jones
[Person: Sue Jones, 110000]
Jones
<__main__.Manager object at 0x02A5AE30>
... |
We could avoid that with
a different coding, but we would still have to redefine __str__ to catch printing, albeit
differently here (self.person would cause this __getattribute__ to fail):
_# Code __getattribute__ differently to minimize extra calls_
```
class Manager:
def __init__(self, name, pay):
self.p... |
Our only direct
options seem to be using __getattr__ and Python 2.6, or redefining operator overloading methods in wrapper classes redundantly in 3.0.
Again, this isn’t an impossible task; many wrappers can predict the set of operator
overloading methods required, and tools and superclasses can automate part of this
t... |
Moreover, not all classes use operator overloading methods (indeed, most application classes usually should not). |
It is, however, something to keep in mind for delegation coding models used in Python 3.0; when operator overloading methods are part
of an object’s interface, wrappers must accommodate them portably by redefining them
locally.
###### Example: Attribute Validations
To close out this chapter, let’s turn to a more real... |
The example we will use defines a CardHolder object
with four attributes, three of which are managed. The managed attributes validate or
transform values when fetched or stored. |
All four versions produce the same results for
the same test code, but they implement their attributes in very different ways. |
The
examples are included largely for self-study; although I won’t go through their code in
detail, they all use concepts we’ve already explored in this chapter.
###### Using Properties to Validate
Our first coding uses properties to manage three attributes. |
As usual, we could use
simple methods instead of managed attributes, but properties help if we have been
using attributes in existing code already. |
Properties run code automatically on attribute
access, but are focused on a specific set of attributes; they cannot be used to intercept
all attributes generically.
**|**
-----
To understand this code, it’s crucial to notice that the attribute assignments inside the
```
__init__ constructor method trigger property ... |
When this method
```
assigns to self.name, for example, it automatically invokes the setName method, which
transforms the value and assigns it to an instance attribute called __name so it won’t
clash with the property’s name.
This renaming (sometimes called name mangling) is necessary because properties use
common in... |
Data is stored in an attribute called
```
__name, and the attribute called name is always a property, not data.
```
In the end, this class 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 virtual... |
For comparison purposes, this propertybased coding weighs in at 39 lines of code:
```
class CardHolder:
acctlen = 8 # Class data
retireage = 59.5
def __init__(self, acct, name, age, addr):
self.acct = acct # Instance data
self.name = name # These trigger pr... |
We’ll use this same testing code for all four versions of
this example. When it runs, we make two instances of our managed-attribute class and
fetch and change its various attributes. |
Operations expected to fail are wrapped in
```
try statements:
bob = CardHolder('1234-5678', 'Bob Smith', 40, '123 main st')
print(bob.acct, bob.name, bob.age, bob.remain, bob.addr, sep=' / ')
bob.name = 'Bob Q. |
Smith'
bob.age = 50
bob.acct = '23-45-67-89'
print(bob.acct, bob.name, bob.age, bob.remain, bob.addr, sep=' / ')
sue = CardHolder('5678-12-34', 'Sue Jones', 35, '124 main st')
print(sue.acct, sue.name, sue.age, sue.remain, sue.addr, sep=' / ')
try:
sue.age = 200
except:
print('Bad age for Sue')
... |
Trace through this code to see how the class’s methods are invoked; accounts
are displayed with some digits hidden, names are converted to a standard format, and
time remaining until retirement is computed when fetched using a class attribute cutoff:
```
12345*** / bob_smith / 40 / 19.5 / 123 main st
23456*** / bob... |
As we’ve seen,
descriptors are very similar to properties in terms of functionality and roles; in fact,
properties are basically a restricted form of descriptor. |
Like properties, descriptors are
**|**
-----
designed to handle specific attributes, not generic attribute access. |
Unlike properties,
descriptors have their own state, and they’re a more general scheme.
To understand this code, it’s again important to notice that the attribute assignments
inside the __init__ constructor method trigger descriptor __set__ methods. |
When the
constructor method assigns to `self.name, for example, it automatically invokes the`
```
Name.__set__() method, which transforms the value and assigns it to a descriptor at
```
tribute called name.
Unlike in the prior property-based variant, though, in this case the actual name value is
attached to the descri... |
Although we could store
this value in either instance or descriptor state, the latter avoids the need to mangle
names with underscores to avoid collisions. |
In the CardHolder client class, the attribute
called name is always a descriptor object, not data.
In the end, this class implements the same attributes as the prior version: it manages
attributes called name, age, and acct; allows the attribute addr to be accessed directly;
and provides a read-only attribute called r... |
Notice how we must catch assignments to the remain name in its descriptor
and raise an exception; as we learned earlier, if we did not do this, assigning to this
attribute of an instance would silently create an instance attribute that hides the class
attribute descriptor. |
For comparison purposes, this descriptor-based coding takes 45
lines of code:
```
class CardHolder:
acctlen = 8 # Class data
retireage = 59.5
def __init__(self, acct, name, age, addr):
self.acct = acct # Instance data
self.name = name # These trigger __s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.