Text
stringlengths
1
9.41k
The following sections provide an overview of each of these additional features, available for new-style class in Python 2.6 and all classes in Python 3.0. ###### Instance Slots By assigning a sequence of string attribute names to a special __slots__ class attribute, it is possible for a new-style class to both limit...
However, like all names in Python, ``` instance attribute names must still be assigned before they can be referenced, even if they’re listed in __slots__.
For example: ``` >>> class limiter(object): ...
__slots__ = ['age', 'name', 'job'] ... >>> x = limiter() ``` `>>> x.age` _# Must assign before use_ ``` AttributeError: age >>> x.age = 40 >>> x.age 40 ``` `>>> x.ape = 1000` _# Illegal: not in __slots___ ``` AttributeError: 'limiter' object has no attribute 'ape' ``` Slots are something of a break wit...
However, this feature is envisioned as both a way to catch “typo” errors like this (assignments to illegal attribute names not in ``` __slots__ are detected), as well as an optimization mechanism.
Allocating a namespace ``` dictionary for every instance object can become expensive in terms of memory if many instances are created and only a few attributes are required.
To save space and speed execution (to a degree that can vary per program), instead of allocating a dictionary for each instance, slot attributes are stored sequentially for quicker lookup. ###### Slots and generic code In fact, some instances with slots may not have a __dict__ attribute dictionary at all, which can m...
Tools that generically list attributes or access attributes by string name, for example, must be careful to use more storage-neutral tools than __dict__, such as the **|** ----- ``` getattr, setattr, and dir built-in functions, which apply to attributes based on either __dict__ or __slots__ storage.
In some cases, both attribute sources may need to be ``` queried for completeness. For example, when slots are used, instances do not normally have an attribute dictionary—Python uses the class descriptors feature covered in Chapter 37 to allocate space for slot attributes in the instance instead.
Only names in the slots list can be assigned to instances, but slot-based attributes can still be fetched and set by name using generic tools.
In Python 3.0 (and in 2.6 for classes derived from object): ``` >>> class C: ``` `...
__slots__ = ['a', 'b']` _# __slots__ means no __dict__ by default_ ``` ... >>> X = C() >>> X.a = 1 >>> X.a 1 >>> X.__dict__ AttributeError: 'C' object has no attribute '__dict__' >>> getattr(X, 'a') 1 ``` `>>> setattr(X, 'b', 2)` _# But getattr() and setattr() still work_ ``` >>> X.b 2 ``` `>>> ...
__slots__ = ['a', 'b'] ``` `...
def __init__(self): self.d = 4` _# Cannot add new names if no __dict___ ``` ... >>> X = D() AttributeError: 'D' object has no attribute 'd' ``` However, extra attributes can still be accommodated by including `__dict__ in` ``` __slots__, in order to allow for an attribute namespace dictionary.
In this case, both ``` storage mechanisms are used, but generic tools such as getattr allow us to treat them as a single set of attributes: ``` >>> class D: ``` `...
__slots__ = ['a', 'b', '__dict__']` _# List __dict__ to include one too_ `... c = 3` _# Class attrs work normally_ `...
def __init__(self): self.d = 4` _# d put in __dict__, a in __slots___ ``` ... >>> X = D() >>> X.d 4 ``` `>>> X.__dict__` _# Some objects have both __dict__ and __slots___ ``` {'d': 4} # getattr() can fetch either type of attr ``` **|** ----- ``` >>> X.__slots__ ['a', 'b', '__dict__'] >>...
print(attr, '=>', getattr(X, attr)) d => 4 a => 1 b => 2 __dict__ => {'d': 4} ``` Since either can be omitted, this is more correctly coded as follows (getattr allows for defaults): ``` >>> for attr in list(getattr(X, '__dict__', [])) + getattr(X, '__slots__', []): ...
print(attr, '=>', getattr(X, attr)) d => 4 a => 1 b => 2 __dict__ => {'d': 4} ###### Multiple __slot__ lists in superclasses ``` Note, however, that this code addresses only slot names in the lowest `__slots__ at-` tribute inherited by an instance.
If multiple classes in a class tree have their own ``` __slots__ attributes, generic programs must develop other policies for listing attributes ``` (e.g., classifying slot names as attributes of classes, not instances). Slot declarations can appear in multiple classes in a class tree, but they are subject to a numbe...
__slots__ = ['c', 'd']` _# Superclass has slots_ ``` ... >>> class D(E): ``` `...
__slots__ = ['a', '__dict__']` _# So does its subclass_ ``` ... >>> X = D() ``` `>>> X.a = 1; X.b = 2; X.c = 3` _# The instance is the union_ ``` >>> X.a, X.c (1, 3) ``` `>>> E.__slots__` _# But slots are not concatenated_ ``` ['c', 'd'] >>> D.__slots__ ['a', '__dict__'] ``` `>>> X.__slots__` _# Instan...
print(attr, '=>', getattr(X, attr)) ... b => 2 # Superclass slots missed! a => 1 __dict__ => {'b': 2} ``` `>>> dir(X)` _# dir() includes all slot names_ ``` [...many names omitted...
'a', 'b', 'c', 'd'] ``` When such generality is possible, slots are probably best treated as class attributes, rather than trying to mold them to appear the same as normal instance attributes.
For more on slots in general, see the Python standard manual set.
Also watch for an example that allows for attributes based on both `__slots__ and` `__dict__ storage in the` ``` Private decorator discussion of Chapter 38. ``` For a prime example of why generic programs may need to care about slots, see the _lister.py display mix-in classes example in the multiple inheritance sectio...
In such a tool that attempts to list attributes generically, slot usage requires either extra code or the implementation of policies regarding the handling of slot-based attributes in general. **|** ----- ###### Class Properties A mechanism known as properties provides another way for new-style classes to define a...
At least for specific attributes, this feature is an alternative to many current uses of the ``` __getattr__ and __setattr__ overloading methods we studied in Chapter 29.
Proper ``` ties have a similar effect to these two methods, but they incur an extra method call for any accesses to names that require dynamic computation.
Properties (and slots) are based on a new notion of attribute descriptors, which is too advanced for us to cover here. In short, a property is a type of object assigned to a class attribute name.
A property is generated by calling the property built-in with three methods (handlers for get, set, and delete operations), as well as a docstring; if any argument is passed as None or omitted, that operation is not supported.
Properties are typically assigned at the top level of a ``` class statement [e.g., name = property(...)].
When thus assigned, accesses to the class ``` attribute itself (e.g., obj.name) are automatically routed to one of the accessor methods passed into the property.
For example, the __getattr__ method allows classes to intercept undefined attribute references: ``` >>> class classic: ... def __getattr__(self, name): ... if name == 'age': ... return 40 ...
else: ...
raise AttributeError ... >>> x = classic() ``` `>>> x.age` _# Runs __getattr___ ``` 40 ``` `>>> x.name` _# Runs __getattr___ ``` AttributeError ``` Here is the same example, coded with properties instead (note that properties are available for all classes but require the new-style object derivation in 2.6 to...
def getage(self): ... return 40 ``` `...
age = property(getage, None, None, None)` _# get, set, del, docs_ ``` ... >>> x = newprops() ``` `>>> x.age` _# Runs getage_ ``` 40 ``` `>>> x.name` _# Normal fetch_ ``` AttributeError: newprops instance has no attribute 'name' ``` **|** ----- For some coding tasks, properties can be less complex and quic...
For example, when we add attribute _assignment support,_ properties become more attractive—there’s less code to type, and no extra method calls are incurred for assignments to attributes we don’t wish to compute dynamically: ``` >>> class newprops(object): ...
def getage(self): ... return 40 ... def setage(self, value): ... print('set age:', value) ... self._age = value ...
age = property(getage, setage, None, None) ... >>> x = newprops() ``` `>>> x.age` _# Runs getage_ ``` 40 ``` `>>> x.age = 42` _# Runs setage_ ``` set age: 42 ``` `>>> x._age` _# Normal fetch; no getage call_ ``` 42 ``` `>>> x.job = 'trainer'` _# Normal assign; no setage call_ `>>> x.job` _# Normal fetch; ...
def __getattr__(self, name):` _# On undefined reference_ ``` ... if name == 'age': ... return 40 ... else: ... raise AttributeError ``` `...
def __setattr__(self, name, value):` _# On all assignments_ ``` ... print('set:', name, value) ... if name == 'age': ... self.__dict__['_age'] = value ... else: ...
self.__dict__[name] = value ... >>> x = classic() ``` `>>> x.age` _# Runs __getattr___ ``` 40 ``` `>>> x.age = 41` _# Runs __setattr___ ``` set: age 41 ``` `>>> x._age` _# Defined: no __getattr__ call_ ``` 41 ``` `>>> x.job = 'trainer'` _# Runs __setattr__ again_ `>>> x.job` _# Defined: no __getattr__ cal...
However, some applications of ``` __getattr__ and __setattr__ may still require more dynamic or generic interfaces than ``` properties directly provide.
For example, in many cases, the set of attributes to be supported cannot be determined when the class is coded, and may not even exist in any tangible form (e.g., when delegating arbitrary method references to a wrapped/ embedded object generically).
In such cases, a generic __getattr__ or a __setattr__ attribute handler with a passed-in attribute name may be preferable.
Because such generic handlers can also handle simpler cases, properties are often an optional extension. For more details on both options, stay tuned for Chapter 37 in the final part of this book.
As we’ll see there, it’s also possible to code properties using function decorator _syntax, a topic introduced later in this chapter._ ###### __getattribute__ and Descriptors The __getattribute__ method, available for new-style classes only, allows a class to intercept all attribute references, not just undefined ref...
It is also somewhat trickier to use than `__getattr__: it is prone to loops, much like` ``` __setattr__, but in different ways. ``` In addition to properties and operator overloading methods, Python supports the notion of attribute descriptors—classes with __get__ and __set__ methods, assigned to class attributes and ...
Descriptors are in a sense a more general form of properties; in fact, properties are a simplified way to define a specific type of descriptor, one that runs functions on access.
Descriptors are also used to implement the slots feature we met earlier. Because properties, __getattribute__, and descriptors are somewhat advanced topics, we’ll defer the rest of their coverage, as well as more on properties, to Chapter 37 in the final part of this book. ###### Metaclasses Most of the changes and ...
As we’ve seen, in 3.0, this merging is complete: classes are now types, and types are classes. Along with these changes, Python also grew a more coherent protocol for coding _metaclasses, which are classes that subclass the type object and intercept class creation_ calls.
As such, they provide a well-defined hook for management and augmentation of class objects.
They are also an advanced topic that is optional for most Python programmers, so we’ll postpone further details here.
We’ll meet metaclasses briefly later **|** ----- in this chapter in conjunction with class decorators, and we’ll explore them in full detail in Chapter 39, in the final part of this book. ###### Static and Class Methods As of Python 2.2, it is possible to define two kinds of methods within a class that can be cal...
In Python 3.0, instance-less methods called only through a class name do not require a staticmethod declaration, but such methods called through instances do. ###### Why the Special Methods? As we’ve learned, a class method is normally passed an instance object in its first argument, to serve as the implied subject o...
Today, though, there are two ways to modify this model.
Before I explain what they are, I should explain why this might matter to you. Sometimes, programs need to process data associated with classes instead of instances. Consider keeping track of the number of instances created from a class, or maintaining a list of all of a class’s instances that are currently in memory.
This type of information and its processing are associated with the class rather than its instances.
That is, the information is usually stored on the class itself and processed in the absence of any instance. For such tasks, simple functions coded outside a class can often suffice—because they can access class attributes through the class name, they have access to class data and never require access to an instance.
However, to better associate such code with a class, and to allow such processing to be customized with inheritance as usual, it would be better to code these types of functions inside the class itself.
To make this work, we need methods in a class that are not passed, and do not expect, a `self instance` argument. Python supports such goals with the notion of static methods—simple functions with no self argument that are nested in a class and are designed to work on class attributes instead of instance attributes.
Static methods never receive an automatic self argument, whether called through a class or an instance.
They usually keep track of information that spans all instances, rather than providing behavior for instances. **|** ----- Although less commonly used, Python also supports the notion of _class methods—_ methods of a class that are passed a class object in their first argument instead of an instance, regardless of ...
Such methods can access class data through their self class argument even if called through an instance.
Normal methods (now known in formal circles as instance methods) still receive a subject instance when called; static and class methods do not. ###### Static Methods in 2.6 and 3.0 The concept of static methods is the same in both Python 2.6 and 3.0, but its implementation requirements have evolved somewhat in Python...
Since this book covers both versions, I need to explain the differences in the two underlying models before we get to the code. Really, we already began this story in the preceding chapter, when we explored the notion of unbound methods.
Recall that both Python 2.6 and 3.0 always pass an instance to a method that is called through an instance.
However, Python 3.0 treats methods fetched directly from a class differently than 2.6: - In Python 2.6, fetching a method from a class produces an unbound method, which cannot be called without manually passing an instance. - In Python 3.0, fetching a method from a class produces a simple function, which can be cal...
By contrast, in Python 3.0 we are required to pass an instance to a method only if the method expects one—methods without a self instance argument can be called through the class without passing an instance.
That is, 3.0 allows simple functions in a class, as long as they do not expect and are not passed an instance argument.
The net effect is that: - In Python 2.6, we must always declare a method as static in order to call it without an instance, whether it is called through a class or an instance. - In Python 3.0, we need not declare such methods as static if they will be called through a class only, but we must do so in order to call...
The following file, spam.py, makes a first attempt—its class has a counter stored as a class attribute, a constructor that bumps up the counter by one each time a new instance is created, and a method that displays the counter’s value. Remember, class attributes are shared by all instances.
Therefore, storing the counter in the class object itself ensures that it effectively spans all instances: ``` class Spam: numInstances = 0 def __init__(self): Spam.numInstances = Spam.numInstances + 1 ``` **|** ----- ``` def printNumInstances(): print("Number of instances created: ", Spam...
Because of that, we want to be able to call it without having to pass an instance.
Indeed, we don’t want to make an instance to fetch the number of instances, because this would change the number of instances we’re trying to fetch!
In other words, we want a self-less “static” method. Whether this code works or not, though, depends on which Python you use, and which way you call the method—through the class or through an instance.
In 2.6 (and 2.X in general), calls to a self-less method function through both the class and instances fail (I’ve omitted some error text here for space): ``` C:\misc> c:\python26\python >>> from spam import Spam ``` `>>> a = Spam()` _# Cannot call unbound class methods in 2.6_ `>>> b = Spam()` _# Methods expect a...
Even though there are no arguments in the def header, the method still expects an instance to be passed in when it’s called, because the function is associated with a class.
In Python 3.0 (and later 3.X releases), calls to self-less methods made through classes work, but calls from instances fail: ``` C:\misc> c:\python30\python >>> from spam import Spam ``` `>>> a = Spam()` _# Can call functions in class in 3.0_ `>>> b = Spam()` _# Calls through instances still pass a self_ ``` >>>...
On the other hand, calls made through an _instance fail in both Pythons, because an instance is automatically passed to a method_ that does not have an argument to receive it: ``` Spam.printNumInstances() # Fails in 2.6, works in 3.0 instance.printNumInstances() # Fails in both 2.6 and 3.0 ``` If you’re ...
However, to allow self-less methods to be **|** ----- called through classes in 2.6 and through instances in both 2.6 and 3.0, you need to either adopt other designs or be able to somehow mark such methods as special.
Let’s look at both options in turn. ###### Static Method Alternatives Short of marking a self-less method as special, there are a few different coding structures that can be tried.
If you want to call functions that access class members without an instance, perhaps the simplest idea is to just make them simple functions outside the class, not class methods.
This way, an instance isn’t expected in the call.
For example, the following mutation of spam.py works the same in Python 3.0 and 2.6 (albeit displaying extra parentheses in 2.6 for its print statement): ``` def printNumInstances(): print("Number of instances created: ", Spam.numInstances) class Spam: numInstances = 0 def __init__(self): Spam.num...
Also, note that the name of the function becomes global, but only to this single module; it will not clash with names in other files of the program. Prior to static methods in Python, this structure was the general prescription.
Because Python already provides modules as a namespace-partitioning tool, one could argue that there’s not typically any need to package functions in classes unless they implement object behavior.
Simple functions within modules like the one here do much of what instance-less class methods could, and are already associated with the class because they live in the same module. Unfortunately, this approach is still less than ideal.
For one thing, it adds to this file’s scope an extra name that is used only for processing a single class.
For another, the function is much less directly associated with the class; in fact, its definition could be hundreds of lines away.
Perhaps worse, simple functions like this cannot be customized by inheritance, since they live outside a class’s namespace: subclasses cannot directly replace or extend such a function by redefining it. **|** ----- We might try to make this example work in a version-neutral way by using a normal method and always c...
A better solution would be to somehow mark a method inside a class as never requiring an instance.
The next section shows how. ###### Using Static and Class Methods Today, there is another option for coding simple functions associated with a class that may be called through either the class or its instances.
As of Python 2.2, we can code classes with static and class methods, neither of which requires an instance argument to be passed in when invoked.
To designate such methods, classes call the built-in functions staticmethod and classmethod, as hinted in the earlier discussion of new-style classes.
Both mark a function object as special—i.e., as requiring no instance if static and requiring a class argument if a class method.
For example: ``` class Methods: def imeth(self, x): # Normal instance method: passed a self print(self, x) def smeth(x): # Static: no instance passed print(x) def cmeth(cls, x): # Class: gets class, not instance print(cls, x) smeth = staticmethod(smeth) # Make sme...
Attributes are created and changed by any assignment in a class ``` statement, so these final assignments simply overwrite the assignments made earlier by the defs. **|** ----- Technically, Python now supports three kinds of class-related methods: _instance,_ _static, and_ _class.