Text
stringlengths
1
9.41k
What are the names and roles of string object types in Python 2.6? 3. What is the mapping between 2.6 and 3.0 string types? 4. How do Python 3.0’s string types differ in terms of operations? 5.
How can you code non-ASCII Unicode characters in a string in 3.0? 6. What are the main differences between text- and binary-mode files in Python 3.0? 7.
How would you read a Unicode text file that contains text in a different encoding than the default for your platform? 8. How can you create a Unicode text file in a specific encoding format? 9.
Why is ASCII text considered to be a kind of Unicode text? 10. How large an impact does Python 3.0’s string types change have on your code? ###### Test Your Knowledge: Answers 1.
Python 3.0 has three string types: str (for Unicode text, including ASCII), bytes (for binary data with absolute byte values), and `bytearray (a mutable flavor of` ``` bytes).
The str type usually represents content stored on a text file, and the other ``` two types generally represent content stored on binary files. **|** ----- 2.
Python 2.6 has two main string types: `str (for 8-bit text and binary data) and` ``` unicode (for wide-character text).
The str type is used for both text and binary file ``` content; unicode is used for text file content that is generally more complex than 8 bits.
Python 2.6 (but not earlier) also has 3.0’s bytearray type, but it’s mostly a back-port and doesn’t exhibit the sharp text/binary distinction that it does in 3.0. 3.
The mapping from 2.6 to 3.0 string types is not direct, because 2.6’s str equates to both str and bytes in 3.0, and 3.0’s str equates to both str and unicode in 2.6. The mutability of bytearray in 3.0 is also unique. 4.
Python 3.0’s string types share almost all the same operations: method calls, sequence operations, and even larger tools like pattern matching work the same way. On the other hand, only `str supports string formatting operations, and` ``` bytearray has an additional set of operations that perform in-place changes.
The str and bytes types also have methods for encoding and decoding text, ``` respectively. 5.
Non-ASCII Unicode characters can be coded in a string with both hex (\xNN) and Unicode (\uNNNN, \UNNNNNNNN) escapes.
On some keyboards, some non-ASCII characters—certain Latin-1 characters, for example—can also be typed directly. 6.
In 3.0, text-mode files assume their file content is Unicode text (even if it’s ASCII) and automatically decode when reading and encode when writing.
With binarymode files, bytes are transferred to and from the file unchanged.
The contents of text-mode files are usually represented as str objects in your script, and the contents of binary files are represented as bytes (or bytearray) objects.
Text-mode files also handle the BOM for certain encoding types and automatically translate endof-line sequences to and from the single \n character on input and output unless this is explicitly disabled; binary-mode files do not perform either of these steps. 7.
To read files encoded in a different encoding than the default for your platform, simply pass the name of the file’s encoding to the `open built-in in 3.0` (codecs.open() in 2.6); data will be decoded per the specified encoding when it is read from the file.
You can also read in binary mode and manually decode the bytes to a string by giving an encoding name, but this involves extra work and is somewhat error-prone for multibyte characters (you may accidentally read a partial character sequence). 8.
To create a Unicode text file in a specific encoding format, pass the desired encoding name to open in 3.0 (codecs.open() in 2.6); strings will be encoded per the desired encoding when they are written to the file.
You can also manually encode a string to bytes and write it in binary mode, but this is usually extra work. 9.
ASCII text is considered to be a kind of Unicode text, because its 7-bit range of values is a subset of most Unicode encodings.
For example, valid ASCII text is also valid Latin-1 text (Latin-1 simply assigns the remaining possible values in an 8-bit byte to additional characters) and valid UTF-8 text (UTF-8 defines a variable-byte scheme for representing more characters, but ASCII characters are still represented with the same codes, in a sing...
The impact of Python 3.0’s string types change depends upon the types of strings you use.
For scripts that use simple ASCII text, there is probably no impact at all: the str string type works the same in 2.6 and 3.0 in this case.
Moreover, although string-related tools in the standard library such as re, struct, pickle, and xml may technically use different types in 3.0 than in 2.6, the changes are largely irrelevant to most programs because 3.0’s str and bytes and 2.6’s str support almost identical interfaces.
If you process Unicode data, the toolset you need has simply moved from 2.6’s unicode and codecs.open() to 3.0’s str and open.
If you deal with binary data files, you’ll need to deal with content as bytes objects; since they have a similar interface to 2.6 strings, though, the impact should again be minimal. **|** ----- ----- ###### CHAPTER 37 ### Managed Attributes This chapter expands on the attribute interception techniques introduced...
Like everything in this part of the book, this chapter is classified as an advanced topic and optional reading, because most applications programmers don’t need to care about the material discussed here—they can fetch and set attributes on objects without concern for attribute implementations.
Especially for tools builders, though, managing attribute access can be an important part of flexible APIs. ###### Why Manage Attributes? Object attributes are central to most Python programs—they are where we often store information about the entities our scripts process.
Normally, attributes are simply names for objects; a person’s `name attribute, for example, might be a simple string,` fetched and set with basic attribute syntax: ``` person.name # Fetch attribute value ``` `person.name = value` _# Change attribute value_ In most cases, the attribute lives in the object it...
That basic model suffices for most programs you will write in your Python career. Sometimes, though, more flexibility is required.
Suppose you’ve written a program to use a name attribute directly, but then your requirements change—for example, you decide that names should be validated with logic when set or mutated in some way when fetched.
It’s straightforward to code methods to manage access to the attribute’s value (valid and transform are abstract here): ``` class Person: def getName(self): if not valid(): raise TypeError('cannot fetch name') else: return self.name.transform() ``` ----- ``` def setName(self, va...
Moreover, this approach requires the program to be aware of how values are exported: as simple names or called methods.
If you begin with a method-based interface to data, clients are immune to changes; if you do not, they can become problematic. This issue can crop up more often than you might expect.
The value of a cell in a spreadsheet-like program, for instance, might begin its life as a simple discrete value, but later mutate into an arbitrary calculation.
Since an object’s interface should be flexible enough to support such future changes without breaking existing code, switching to methods later is less than ideal. ###### Inserting Code to Run on Attribute Access A better solution would allow you to run code automatically on attribute access, if needed.
At various points in this book, we’ve met Python tools that allow our scripts to dynamically compute attribute values when fetching them and validate or change attribute values when storing them.
In this chapter, were going to expand on the tools already introduced, explore other available tools, and study some larger use-case examples in this domain.
Specifically, this chapter presents: - The __getattr__ and __setattr__ methods, for routing undefined attribute fetches and all attribute assignments to generic handler methods. - The __getattribute__ method, for routing all attribute fetches to a generic handler method in new-style classes in 2.6 and all classes i...
They do differ in some important ways, though.
For example, the last two techniques listed here apply to specific attributes, whereas the first two are generic enough to be used by delegation-based classes that **|** ----- must route arbitrary attributes to wrapped objects.
As we’ll see, all four schemes also differ in both complexity and aesthetics, in ways you must see in action to judge for yourself. Besides studying the specifics behind the four attribute interception techniques listed in this section, this chapter also presents an opportunity to explore larger programs than we’ve se...
The CardHolder case study at the end, for example, should serve as a self-study example of larger classes in action.
We’ll also be using some of the techniques outlined here in the next chapter to code decorators, so be sure you have at least a general understanding of these topics before you move on. ###### Properties The property protocol allows us to route a specific attribute’s get and set operations to functions or methods we ...
As such, they are inherited by subclasses and instances, like any other class attributes.
Their access-interception functions are provided with the ``` self instance argument, which grants access to state information and class attributes ``` available on the subject instance. A property manages a single, specific attribute; although it can’t catch all attribute accesses generically, it allows us to contro...
As we’ll see, properties are strongly related to descriptors; they are essentially a restricted form of them. ###### The Basics A property is created by assigning the result of a built-in function to a class attribute: ``` attribute = property(fget, fset, fdel, doc) ``` None of this built-in’s arguments are requir...
When using them, we pass fget a function for intercepting attribute fetches, fset a function for assignments, and fdel a function for attribute deletions; the doc argument receives a documentation string for the attribute, if desired (otherwise the property copies the docstring of fget, if provided, which defaults to N...
fget returns the computed attribute value, and fset and fdel return nothing (really, None). This built-in call returns a property object, which we assign to the name of the attribute to be managed in the class scope, where it will be inherited by every instance. **|** ----- ###### A First Example To demonstrate h...
When this code is run, two instances inherit the property, just as they would any other attribute attached to their class.
However, their attribute accesses are caught: ``` fetch... Bob Smith change... fetch... Robert Smith remove... ------------------- fetch... Sue Jones name property docs ``` Like all class attributes, properties are inherited by both instances and lower subclasses. If we change our example as follows...
In terms of inheritance, properties work the same as normal methods; because they have access to the self instance argument, they can access instance state information like methods, as the next section demonstrates. ###### Computed Attributes The example in the prior section simply traces attribute accesses.
Usually, though, properties do much more—computing the value of an attribute dynamically when fetched, for example.
The following example illustrates: ``` class PropSquare: def __init__(self, start): self.value = start def getX(self): # On attr fetch return self.value ** 2 def setX(self, value): # On attr assign self.value = value X = property(getX, setX) # No delete or ...
The effect is much like an implicit method call.
When the code is run, the value is stored in the instance as state information, but each time we fetch it via the managed attribute, its value is automatically squared: ``` 9 16 1024 ``` Notice that we’ve made two different instances—because property methods automatically receive a self argument, they have acces...
In our case, this mean the fetch computes the square of the subject instance’s data. **|** ----- ###### Coding Properties with Decorators Although we’re saving additional details until the next chapter, we introduced function decorator basics earlier, in Chapter 31.
Recall that the function decorator syntax: ``` @decorator def func(args): ... ``` is automatically translated to this equivalent by Python, to rebind the function name to the result of the decorator callable: ``` def func(args): ... func = decorator(func) ``` Because of this mapping, it turns out that the pro...
# Rebinds: name = property(name) ``` When run, the decorated method is automatically passed to the first argument of the ``` property built-in.
This is really just alternative syntax for creating a property and re ``` binding the attribute name manually: ``` class Person: def name(self): ... name = property(name) ``` As of Python 2.6, property objects also have getter, setter, and deleter methods that assign the corresponding property accessor metho...
We can use these to specify components of properties by decorating normal methods too, though the getter component is usually filled in automatically by the act of creating the property itself: ``` class Person: def __init__(self, name): self._name = name @property def name(self): # name = p...
When it’s run, the results are the same: ``` fetch... Bob Smith change... fetch... Robert Smith remove... ------------------- fetch... Sue Jones name property docs ``` Compared to manual assignment of property results, in this case using decorators to code properties requires just three extra lines ...
As is so often the case with alternative tools, the choice between the two techniques is largely subjective. ###### Descriptors _Descriptors provide an alternative way to intercept attribute access; they are strongly_ related to the properties discussed in the prior section.
In fact, a property is a kind of descriptor—technically speaking, the property built-in is just a simplified way to create a specific type of descriptor that runs method functions on attribute accesses. Functionally speaking, the descriptor protocol allows us to route a specific attribute’s get and set operations to m...
Like any other class attribute, they are inherited by subclasses and instances.
Their access-interception methods are provided with both a ``` self for the descriptor itself, and the instance of the client class.
Because of this, they ``` can retain and use state information of their own, as well as state information of the subject instance.
For example, a descriptor may call methods available in the client class, as well as descriptor-specific methods it defines. **|** ----- Like a property, a descriptor manages a single, specific attribute; although it can’t catch all attribute accesses generically, it provides control over both fetch and assignment ...
Properties really are just a convenient way to create a specific kind of descriptor, and as we shall see, they can be coded as descriptors directly. Whereas properties are fairly narrow in scope, descriptors provide a more general solution.
For instance, because they are coded as normal classes, descriptors have their own state, may participate in descriptor inheritance hierarchies, can use composition to aggregate objects, and provide a natural structure for coding internal methods and attribute documentation strings. ###### The Basics As mentioned pre...
# Return attr value def __set__(self, instance, value): ... # Return nothing (None) def __delete__(self, instance): ...
# Return nothing (None) ``` Classes with any of these methods are considered descriptors, and their methods are special when one of their instances is assigned to another class’s attribute—when the attribute is accessed, they are automatically invoked.
If any of these methods are absent, it generally means that the corresponding type of access is not supported.
Unlike with properties, however, omitting a __set__ allows the name to be redefined in an instance, thereby hiding the descriptor—to make an attribute _read-only, you must define_ ``` __set__ to catch assignments and raise an exception. ###### Descriptor method arguments ``` Before we code anything realistic, let’s t...
All three descriptor methods outlined in the prior section are passed both the descriptor class instance (self) and the instance of the client class to which the descriptor instance is attached (instance). The __get__ access method additionally receives an owner argument, specifying the class to which the descriptor i...
Its instance argument is either the instance through which the attribute was accessed (for `instance.attr), or` `None when the at-` tribute is accessed through the owner class directly (for `class.attr).
The former of` these generally computes a value for instance access, and the latter usually returns ``` self if descriptor object access is supported. ``` **|** ----- For example, in the following, when X.attr is fetched, Python automatically runs the ``` __get__ method of the Descriptor class to which the Subject....
def __get__(self, instance, owner): ... print(self, instance, owner, sep='\n') ... >>> class Subject: ``` `...
attr = Descriptor()` _# Descriptor instance is class attr_ ``` ... >>> X = Subject() >>> X.attr <__main__.Descriptor object at 0x0281E690> <__main__.Subject object at 0x028289B0> <class '__main__.Subject'> >>> Subject.attr <__main__.Descriptor object at 0x0281E690> None <class '__main__.Subject'> `...
In the following, the attribute assignment to ``` X.a stores a in the instance object X, thereby hiding the descriptor stored in class C: >>> class D: ...
def __get__(*args): print('get') ... >>> class C: ...
a = D() ... >>> X = C() ``` `>>> X.a` _# Runs inherited descriptor __get___ ``` get >>> C.a get ``` `>>> X.a = 99` _# Stored on X, hiding C.a_ ``` >>> X.a 99 >>> list(X.__dict__.keys()) ``` **|** ----- ``` ['a'] >>> Y = C() ``` `>>> Y.a` _# Y still inherits descriptor_ ``` get >>> C.a g...
To make a descriptor-based attribute read-only, catch the assignment in the descriptor class and raise an exception to prevent attribute assignment—when assigning an attribute that is a descriptor, Python effectively bypasses the normal instance-level assignment behavior and routes the operation to the descriptor objec...
def __get__(*args): print('get') ... def __set__(*args): raise AttributeError('cannot set') ... >>> class C: ...
a = D() ... >>> X = C() ``` `>>> X.a` _# Routed to C.a.__get___ ``` get ``` `>>> X.a = 99` _# Routed to C.a.__set___ ``` AttributeError: cannot set ``` Also be careful not to confuse the descriptor __delete__ method with the general __del__ method.
The former is called on attempts to delete the managed attribute name on an instance of the owner class; the latter is the general instance destructor method, run when an instance of any kind of class is about to be garbage collected.
__delete__ is more closely related to the __delattr__ generic attribute deletion method we’ll meet later in this chapter.
See Chapter 29 for more on operator overloading methods. ###### A First Example To see how this all comes together in more realistic code, let’s get started with the same first example we wrote for properties.
The following defines a descriptor that intercepts access to an attribute named name in its clients.
Its methods use their instance argument to access state information in the subject instance, where the name string is actually stored.
Like properties, descriptors work properly only for new-style classes, so be sure to derive both classes in the following from object if you’re using 2.6: ``` class Name: # Use (object) in 2.6 "name descriptor docs" def __get__(self, instance, owner): print('fetch...') return instanc...
Really, we must assign the descriptor to a class attribute like this—it won’t work if assigned to a self instance attribute instead.
When the descriptor’s __get__ method is run, it is passed three objects to define its context: - self is the Name class instance. - instance is the Person class instance. - owner is the Person class. When this code is run the descriptor’s methods intercept accesses to the attribute, much like the property versio...
In fact, the output is the same again: ``` fetch... Bob Smith change... fetch... Robert Smith remove... ------------------- fetch... Sue Jones name descriptor docs ``` Also like in the property example, our descriptor class instance is a class attribute and thus is inherited by all instances of the ...
If we change the ``` Person class in our example to the following, for instance, the output of our script is ``` the same: **|** ----- ``` ... class Super: def __init__(self, name): self._name = name name = Name() class Person(Super): # Descriptors are inherited pass ... ```...
Here’s what our example looks like if we use a nested class: ``` class Person: def __init__(self, name): self._name = name class Name: # Using a nested class "name descriptor docs" def __get__(self, instance, owner): print('fetch...') return instance._name ...
This version works the same as the original—we’ve simply moved the descriptor class definition into the client class’s scope—but the last line of the testing code must change to fetch the docstring from its new location: ``` ... print(Person.Name.__doc__) # Differs: not Name.__doc__ outside class ###### Computed...