Text
stringlengths
1
9.41k
In fact, there is no way to ever overwrite the value of the object 3—as introduced in Chapter 4, integers are immutable and thus can never be changed in-place. One way to think of this is that, unlike in some languages, in Python variables are always pointers to objects, not labels of changeable memory areas: setting ...
The net effect is that assignment to a variable can impact only the single variable being assigned.
When mutable objects and in-place changes enter the equation, though, the picture changes somewhat; to see how, let’s move on. ###### Shared References and In-Place Changes As you’ll see later in this part’s chapters, there are objects and operations that perform in-place object changes.
For instance, an assignment to an offset in a list actually changes the list object itself in-place, rather than generating a brand new list object. For objects that support such in-place changes, you need to be more aware of shared references, since a change from one name may impact others. To further illustrate, let...
Recall that lists, which do support in-place assignments to positions, are simply collections of other objects, coded in square brackets: ``` >>> L1 = [2, 3, 4] >>> L2 = L1 ``` **f** **|** ----- ``` L1 here is a list containing the objects 2, 3, and 4.
Items inside a list are accessed by their ``` positions, so L1[0] refers to object 2, the first item in the list L1.
Of course, lists are also objects in their own right, just like integers and strings.
After running the two prior assignments, L1 and L2 reference the same object, just like a and b in the prior example (see Figure 6-2).
Now say that, as before, we extend this interaction to say the following: ``` >>> L1 = 24 ``` This assignment simply sets L1 is to a different object; L2 still references the original list.
If we change this statement’s syntax slightly, however, it has a radically different effect: `>>> L1 = [2, 3, 4]` _# A mutable object_ `>>> L2 = L1` _# Make a reference to the same object_ `>>> L1[0] = 24` _# An in-place change_ `>>> L1` _# L1 is different_ ``` [24, 3, 4] ``` `>>> L2` _# But so is L2!_ ``` [24, ...
This sort of change overwrites part of the list object in-place.
Because the ``` list object is shared by (referenced from) other variables, though, an in-place change like this doesn’t only affect L1—that is, you must be aware that when you make such changes, they can impact other parts of your program.
In this example, the effect shows up in L2 as well because it references the same object as L1.
Again, we haven’t actually changed L2, either, but its value will appear different because it has been overwritten. This behavior is usually what you want, but you should be aware of how it works, so that it’s expected.
It’s also just the default: if you don’t want such behavior, you can request that Python copy objects instead of making references.
There are a variety of ways to copy a list, including using the built-in list function and the standard library ``` copy module.
Perhaps the most common way is to slice from start to finish (see Chapters ``` 4 and 7 for more on slicing): ``` >>> L1 = [2, 3, 4] ``` `>>> L2 = L1[:]` _# Make a copy of L1_ ``` >>> L1[0] = 24 >>> L1 [24, 3, 4] ``` `>>> L2` _# L2 is not changed_ ``` [2, 3, 4] ``` Here, the change made through L1 is not r...
Also, note that the standard library copy module has a call for copying any object type generically, as well as a call for copying nested object structures (a dictionary with nested lists, for example): ``` import copy X = copy.copy(Y) # Make top-level "shallow" copy of any object Y X = copy.deepcopy(Y) # M...
For now, keep in mind that objects that can be changed in-place (that is, mutable objects) are always open to these kinds of effects. In Python, this includes lists, dictionaries, and some objects defined with class statements.
If this is not the desired behavior, you can simply copy your objects as needed. ###### Shared References and Equality In the interest of full disclosure, I should point out that the garbage-collection behavior described earlier in this chapter may be more conceptual than literal for certain types. Consider these sta...
Most kinds of objects, though, are reclaimed immediately when they are no longer referenced; for those that are not, the caching mechanism is irrelevant to your code. For instance, because of Python’s reference model, there are two different ways to check for equality in a Python program.
Let’s create a shared reference to demonstrate: ``` >>> L = [1, 2, 3] ``` `>>> M = L` _# M and L reference the same object_ `>>> L == M` _# Same value_ ``` True ``` `>>> L is M` _# Same object_ ``` True ``` The first technique here, the == operator, tests whether the two referenced objects have the same values...
It returns False if the names point to equivalent but different objects, as is the case when we run two different literal expressions: ``` >>> L = [1, 2, 3] ``` `>>> M = [1, 2, 3]` _# M and L reference different objects_ `>>> L == M` _# Same values_ ``` True ``` `>>> L is M` _# Different objects_ ``` False ```...
Because small integers and strings are cached and reused, though, is tells us they reference the same single object. In fact, if you really want to look under the hood, you can always ask Python how many references there are to an object: the getrefcount function in the standard sys module returns the object’s referen...
When I ask about the integer object 1 in the IDLE GUI, for instance, it reports 837 reuses of this same object (most of which are in IDLE’s system code, not mine): ``` >>> import sys ``` `>>> sys.getrefcount(1)` _# 837 pointers to this shared piece of memory_ ``` 837 ``` This object caching and reuse is irrelevan...
Still, this behavior reflects one of the many ways Python optimizes its model for execution speed. ###### Dynamic Typing Is Everywhere Of course, you don’t really need to draw name/object diagrams with circles and arrows to use Python.
When you’re starting out, though, it sometimes helps you understand unusual cases if you can trace their reference structures.
If a mutable object changes out from under you when passed around your program, for example, chances are you are witnessing some of this chapter’s subject matter firsthand. Moreover, even if dynamic typing seems a little abstract at this point, you probably will care about it eventually.
Because _everything seems to work by assignment and_ references in Python, a basic understanding of this model is useful in many different **|** ----- contexts.
As you’ll see, it works the same in assignment statements, function arguments, for loop variables, module imports, class attributes, and more.
The good news is that there is just one assignment model in Python; once you get a handle on dynamic typing, you’ll find that it works the same everywhere in the language. At the most practical level, dynamic typing means there is less code for you to write. Just as importantly, though, dynamic typing is also the root...
As you’ll see, when used well, dynamic typing and the polymorphism it provides produce code that automatically adapts to new requirements as your systems evolve. ###### Chapter Summary This chapter took a deeper look at Python’s dynamic typing model—that is, the way that Python keeps track of object types for us auto...
Along the way, we learned how variables and objects are associated by references in Python; we also explored the idea of garbage collection, learned how shared references to objects can affect multiple variables, and saw how references impact the notion of equality in Python. Because there is just one assignment model...
The following quiz should help you review some of this chapter’s ideas. After that, we’ll resume our object tour in the next chapter, with strings. ###### Test Your Knowledge: Quiz 1.
Consider the following three statements. Do they change the value printed for A? ``` A = "spam" B = A B = "shrubbery" ``` 2. Consider these three statements.
Do they change the printed value of A? ``` A = ["spam"] B = A B[0] = "shrubbery" ``` 3.
How about these—is A changed now? ``` A = ["spam"] B = A[:] B[0] = "shrubbery" ``` **|** ----- ###### Test Your Knowledge: Answers 1. No: A still prints as "spam".
When B is assigned to the string "shrubbery", all that happens is that the variable B is reset to point to the new string object.
A and B initially share (i.e., reference/point to) the same single string object "spam", but two names are never linked together in Python. Thus, setting B to a different object has no effect on `A.
The same would be true if the last statement here was` `B = B +` ``` 'shrubbery', by the way—the concatenation would make a new object for its result, ``` which would then be assigned to B only.
We can never overwrite a string (or number, or tuple) in-place, because strings are immutable. 2. Yes: A now prints as ["shrubbery"].
Technically, we haven’t really changed either ``` A or B; instead, we’ve changed part of the object they both reference (point to) by ``` overwriting that object in-place through the variable B.
Because A references the same object as B, the update is reflected in A as well. 3. No: A still prints as ["spam"].
The in-place assignment through B has no effect this time because the slice expression made a copy of the list object before it was assigned to `B.
After the second assignment statement, there are two different list` objects that have the same value (in Python, we say they are ==, but not is).
The third statement changes the value of the list object pointed to by B, but not that pointed to by A. **|** ----- ###### CHAPTER 7 ### Strings The next major type on our built-in object tour is the Python string—an ordered collection of characters used to store and represent text-based information.
We looked briefly at strings in Chapter 4.
Here, we will revisit them in more depth, filling in some of the details we skipped then. From a functional perspective, strings can be used to represent just about anything that can be encoded as text: symbols and words (e.g., your name), contents of text files loaded into memory, Internet addresses, Python programs,...
They can also be used to hold the absolute binary values of bytes, and multibyte Unicode text used in internationalized programs. You may have used strings in other languages, too.
Python’s strings serve the same role as character arrays in languages such as C, but they are a somewhat higher-level tool than arrays.
Unlike in C, in Python, strings come with a powerful set of processing tools.
Also unlike languages such as C, Python has no distinct type for individual characters; instead, you just use one-character strings. Strictly speaking, Python strings are categorized as immutable sequences, meaning that the characters they contain have a left-to-right positional order and that they cannot be changed i...
In fact, strings are the first representative of the larger class of objects called sequences that we will study here.
Pay special attention to the sequence operations introduced in this chapter, because they will work the same on other sequence types we’ll explore later, such as lists and tuples. Table 7-1 previews common string literals and operations we will discuss in this chapter.
Empty strings are written as a pair of quotation marks (single or double) with nothing in between, and there are a variety of ways to code strings.
For processing, strings support expression operations such as concatenation (combining strings), slicing (extracting sections), indexing (fetching by offset), and so on.
Besides expressions, Python also provides a set of string methods that implement common string-specific tasks, as well as _modules for more advanced text-processing tasks such as pattern_ matching.
We’ll explore all of these later in the chapter. ----- _Table 7-1.
Common string literals and operations_ **Operation** **Interpretation** `S = ''` Empty string `S = "spam's"` Double quotes, same as single `S = 's\np\ta\x00m'` Escape sequences `S = """..."""` Triple-quoted block strings `S = r'\temp\spam'` Raw strings `S = b'spam'` Byte strings in 3.0 (Chapter 36) `S = u'spa...
This book’s scope, though, is focused on the fundamentals represented by Table 7-1. **|** ----- To cover the basics, this chapter begins with an overview of string literal forms and string expressions, then moves on to look at more advanced tools such as string methods and formatting.
Python comes with many string tools, and we won’t look at them all here; the complete story is chronicled in the Python library manual.
Our goal here is to explore enough commonly used tools to give you a representative sample; methods we won’t see in action here, for example, are largely analogous to those we will. _Content note: Technically speaking, this chapter tells only part of the_ string story in Python—the part most programmers need to know.
It presents the basic str string type, which handles ASCII text and works the same regardless of which version of Python you use.
That is, this chapter intentionally limits its scope to the string processing essentials that are used in most Python scripts. From a more formal perspective, ASCII is a simple form of Unicode text. Python addresses the distinction between text and binary data by including distinct object types: - In Python 3....
Because most programmers don’t need to dig into the details of Unicode encodings or binary data formats, though, I’ve moved all such details to the Advanced Topics part of this book, in Chapter 36. If you do need to deal with more advanced string concepts such as alternative character sets or packed binary data and fi...
For now, we’ll focus on the basic string type and its operations.
As you’ll find, the basics we’ll study here also apply directly to the more advanced string types in Python’s toolset. ###### String Literals By and large, strings are fairly easy to use in Python.
Perhaps the most complicated thing about them is that there are so many ways to write them in your code: - Single quotes: 'spa"m' - Double quotes: "spa'm" - Triple quotes: '''...
spam ...''', """...
spam ...""" - Escape sequences: "s\tp\na\0m" - Raw strings: r"C:\new\test.spm" **|** ----- - Byte strings in 3.0 (see Chapter 36): b'sp\x01am' - Unicode strings in 2.6 only (see Chapter 36): u'eggs\u0020spam' The single- and double-quoted forms are by far the most common; the others serve specialized roles,...
Let’s take a quick look at all the other options in turn. ###### Single- and Double-Quoted Strings Are the Same Around Python strings, single and double quote characters are interchangeable.
That is, string literals can be written enclosed in either two single or two double quotes— the two forms work the same and return the same type of object.
For example, the following two strings are identical, once coded: ``` >>> 'shrubbery', "shrubbery" ('shrubbery', 'shrubbery') ``` The reason for supporting both is that it allows you to embed a quote character of the other variety inside a string without escaping it with a backslash.
You may embed a single quote character in a string enclosed in double quote characters, and vice versa: ``` >>> 'knight"s', "knight's" ('knight"s', "knight's") ``` Incidentally, Python automatically concatenates adjacent string literals in any expression, although it is almost as simple to add a + operator between...
You can also embed quotes by escaping them with backslashes: ``` >>> 'knight\'s', "knight\"s" ("knight's", 'knight"s') ``` To understand why, you need to know how escapes work in general. ###### Escape Sequences Represent Special Bytes The last example embedded a quote inside a string by preceding it with a back...
The character \, and one or more characters following it in the string literal, are replaced with a single character in the resulting string object, which has the binary **|** ----- value specified by the escape sequence.
For example, here is a five-character string that embeds a newline and a tab: ``` >>> s = 'a\nb\tc' ``` The two characters \n stand for a single character—the byte containing the binary value of the newline character in your character set (usually, ASCII code 10).
Similarly, the sequence \t is replaced with the tab character. The way this string looks when printed depends on how you print it.
The interactive echo shows the special characters as escapes, but print interprets them instead: ``` >>> s 'a\nb\tc' >>> print(s) a b c ``` To be completely sure how many bytes are in this string, use the built-in len function— it returns the actual number of bytes in a string, regardless of how it is dis...
Note that the original backslash characters are not really stored with the string in memory; they are used to tell Python to store special byte values in the string.
For coding such special bytes, Python recognizes a full set of escape code sequences, listed in Table 7-2. _Table 7-2.
String backslash characters_ **Escape** **Meaning** `\newline` Ignored (continuation line) `\\` Backslash (stores one \) `\'` Single quote (stores ') `\"` Double quote (stores ") `\a` Bell `\b` Backspace `\f` Formfeed `\n` Newline (linefeed) `\r` Carriage return `\t` Horizontal tab `\v` Vertical tab `\xh...
escape sequence takes exactly eight hexadecimal digits (h); both \u and \U can be used only in Unicode string literals. Some escape sequences allow you to embed absolute binary values into the bytes of a string.
For instance, here’s a five-character string that embeds two binary zero bytes (coded as octal escapes of one digit): ``` >>> s = 'a\0b\0c' >>> s 'a\x00b\x00c' >>> len(s) 5 ``` In Python, the zero (null) byte does not terminate a string the way it typically does in C.
Instead, Python keeps both the string’s length and text in memory. In fact, no character terminates a string in Python.
Here’s a string that is all absolute binary escape codes—a binary 1 and 2 (coded in octal), followed by a binary 3 (coded in hexadecimal): ``` >>> s = '\001\002\x03' >>> s '\x01\x02\x03' >>> len(s) 3 ``` Notice that Python displays nonprintable characters in hex, regardless of how they were specified.
You can freely combine absolute value escapes and the more symbolic escape types in Table 7-2.
The following string contains the characters “spam”, a tab and newline, and an absolute zero value byte coded in hex: ``` >>> S = "s\tp\na\x00m" >>> S 's\tp\na\x00m' >>> len(S) 7 >>> print(S) s p a m ``` This becomes more important to know when you process binary data files in Python. Because their ...
In Python 3.0, binary file content is a bytes string, with an interface similar to that of normal strings; in 2.6, such content is a normal str string.
See also the standard struct module introduced in Chapter 9, which can parse binary data loaded from a file, and the extended coverage of binary files and byte strings in Chapter 36. **|** ----- Finally, as the last entry in Table 7-2 implies, if Python does not recognize the character after a \ as being a valid es...
Sometimes, though, the special treatment of backslashes for introducing escapes can lead to trouble.
It’s surprisingly common, for instance, to see Python newcomers in classes trying to open a file with a filename argument that looks something like this: ``` myfile = open('C:\new\text.dat', 'w') ``` thinking that they will open a file called text.dat in the directory C:\new.
The problem here is that \n is taken to stand for a newline character, and \t is replaced with a tab. In effect, the call tries to open a file named C:(newline)ew(tab)ext.dat, with usually less than stellar results. This is just the sort of thing that raw strings are useful for.
If the letter r (uppercase or lowercase) appears just before the opening quote of a string, it turns off the escape mechanism.
The result is that Python retains your backslashes literally, exactly as you type them.
Therefore, to fix the filename problem, just remember to add the letter r on Windows: ``` myfile = open(r'C:\new\text.dat', 'w') ``` Alternatively, because two backslashes are really an escape sequence for one backslash, you can keep your backslashes by simply doubling them up: ``` myfile = open('C:\\new\\text.dat...
The ``` print statement provides a more user-friendly format that shows that there is actually ``` only one backslash in each spot.
To verify this is the case, you can check the result of the built-in len function, which returns the number of bytes in the string, independent of display formats.
If you count the characters in the print(path) output, you’ll see that there really is just 1 character per backslash, for a total of 15. Besides directory paths on Windows, raw strings are also commonly used for regular expressions (text pattern matching, supported with the re module introduced in Chapter 4).
Also note that Python scripts can usually use forward slashes in directory paths on Windows and Unix because Python tries to interpret paths portably (i.e., 'C:/new/ ``` text.dat' works when opening files, too).