Text
stringlengths
1
9.41k
Python’s major built-in object types, organized by categories.
Everything is a type of object_ _in Python, even the type of an object!_ **|** ----- ###### Type Objects In fact, even types themselves are an object type in Python: the type of an object is an object of type type (say that three times fast!).
Seriously, a call to the built-in function ``` type(X) returns the type object of object X.
The practical application of this is that type ``` objects can be used for manual type comparisons in Python if statements.
However, for reasons introduced in Chapter 4, manual type testing is usually not the right thing to do in Python, since it limits your code’s flexibility. One note on type names: as of Python 2.2, each core type has a new built-in name added to support type customization through object-oriented subclassing: dict, list...
Calls to these names are really object ``` constructor calls, not simply conversion functions, though you can treat them as simple functions for basic usage. In addition, the types standard library module in Python 3.0 provides additional type names for types that are not available as built-ins (e.g., the type of a f...
For example, all of the following type tests are true: ``` type([1]) == type([]) # Type of another list type([1]) == list # List type name isinstance([1], list) # List or customization thereof import types # types has names for other types def f(): pass type(f) == types.Fun...
See Chapter 31 for more on subclassing built-in types in Python 2.2 and later. Also in Chapter 31, we will explore how type(X) and type-testing in general apply to instances of user-defined classes.
In short, in Python 3.0 and for new-style classes in Python 2.6, the type of a class instance is the class from which the instance was made. For classic classes in Python 2.6 and earlier, all class instances are of the type “instance,” and we must compare instance __class__ attributes to compare their types meaningfull...
Since we’re not ready for classes yet, we’ll postpone the rest of this story until Chapter 31. ###### Other Types in Python Besides the core objects studied in this part of the book, and the program-unit objects such as functions, modules, and classes that we’ll meet later, a typical Python installation has dozens of...
For instance, to make a regular expression object, you import re and call ``` re.compile().
See Python’s library reference for a comprehensive guide to all the tools ``` available to Python programs. ###### Built-in Type Gotchas That’s the end of our look at core data types.
We’ll wrap up this part of the book with a discussion of common problems that seem to bite new users (and the occasional expert), along with their solutions.
Some of this is a review of ideas we’ve already covered, but these issues are important enough to warn about again here. ###### Assignment Creates References, Not Copies Because this is such a central concept, I’ll mention it again: you need to understand what’s going on with shared references in your program.
For instance, in the following example, the list object assigned to the name L is referenced from L and from inside the list assigned to the name M.
Changing L in-place changes what M references, too: ``` >>> L = [1, 2, 3] ``` `>>> M = ['X', L, 'Y']` _# Embed a reference to L_ ``` >>> M ['X', [1, 2, 3], 'Y'] ``` `>>> L[1] = 0` _# Changes M too_ ``` >>> M ['X', [1, 0, 3], 'Y'] ``` This effect usually becomes important only in larger programs, and shared...
If they’re not, you can avoid sharing objects by copying them explicitly.
For lists, you can always make a top-level copy by using an emptylimits slice: ``` >>> L = [1, 2, 3] ``` `>>> M = ['X', L[:], 'Y']` _# Embed a copy of L_ `>>> L[1] = 0` _# Changes only L, not M_ ``` >>> L [1, 0, 3] >>> M ['X', [1, 2, 3], 'Y'] ``` **|** ----- Remember, slice limits default to 0 and the le...
However, when mutable sequences are nested, the effect might not always be what you expect.
For instance, in the following example X is assigned to L repeated four times, whereas Y is assigned to a list containing `L repeated four times:` ``` >>> L = [4, 5, 6] ``` `>>> X = L * 4` _# Like [4, 5, 6] + [4, 5, 6] + ..._ `>>> Y = [L] * 4` _# [L] + [L] + ...
= [L, L,...]_ ``` >>> X [4, 5, 6, 4, 5, 6, 4, 5, 6, 4, 5, 6] >>> Y [[4, 5, 6], [4, 5, 6], [4, 5, 6], [4, 5, 6]] ``` Because L was nested in the second repetition, Y winds up embedding references back to the original list assigned to L, and so is open to the same sorts of side effects noted in the last section:...
If you remember that repetition, concatenation, and slicing copy only the top level of their operand objects, these sorts of cases make much more sense. ###### Beware of Cyclic Data Structures We actually encountered this concept in a prior exercise: if a collection object contains a reference to itself, it’s called ...
Python prints a [...] whenever it detects a cycle in the object, rather than getting stuck in an infinite loop: `>>> L = ['grail']` _# Append reference to same object_ `>>> L.append(L)` _# Generates cycle in object: [...]_ ``` >>> L ['grail', [...]] ``` Besides understanding that the three dots in square brackets...
For instance, some programs keep a list or dictionary of already visited items and **|** ----- check it to determine whether they’re in a cycle.
See the solutions to the “Test Your Knowledge: Part I Exercises” in Appendix B for more on this problem, and check out the reloadall.py program in Chapter 24 for a solution. Don’t use cyclic references unless you really need to.
There are good reasons to create cycles, but unless you have code that knows how to handle them, you probably won’t want to make your objects reference themselves very often in practice. ###### Immutable Types Can’t Be Changed In-Place You can’t change an immutable object in-place.
Instead, you construct a new object with slicing, concatenation, and so on, and assign it back to the original reference, if needed: ``` T = (1, 2, 3) T[2] = 4 # Error! T = T[:2] + (4,) # OK: (1, 2, 4) ``` That might seem like extra coding work, but the upside is that the previous gotchas can’t happen wh...
We learned that tuples support all the usual sequence operations, have just a few methods, and do not allow any in-place changes because they are immutable.
We also learned that files are returned by the built-in open function and provide methods for reading and writing data.
We explored how to translate Python objects to and from strings for storing in files, and we looked at the pickle and struct modules for advanced roles (object serialization and binary data).
Finally, we wrapped up by reviewing some properties common to all object types (e.g., shared references) and went through a list of common mistakes (“gotchas”) in the object type domain. In the next part, we’ll shift gears, turning to the topic of statement syntax in Python— we’ll explore all of Python’s basic procedu...
Before moving on, though, take the chapter quiz, and then work through the end-of-part lab exercises to review type concepts.
Statements largely just create and process objects, so make sure you’ve mastered this domain by working through all the exercises before reading on. **|** ----- ###### Test Your Knowledge: Quiz 1.
How can you determine how large a tuple is? Why is this tool located where it is? 2. Write an expression that changes the first item in a tuple.
(4, 5, 6) should become ``` (1, 5, 6) in the process. ``` 3. What is the default for the processing mode argument in a file open call? 4.
What module might you use to store Python objects in a file without converting them to strings yourself? 5. How might you go about copying all parts of a nested structure at once? 6.
When does Python consider an object true? 7. What is your quest? ###### Test Your Knowledge: Answers 1.
The built-in len function returns the length (number of contained items) for any container object in Python, including tuples.
It is a built-in function instead of a type method because it applies to many different types of objects.
In general, builtin functions and expressions may span many object types; methods are specific to a single object type, though some may be available on more than one type (index, for example, works on lists and tuples). 2.
Because they are immutable, you can’t really change tuples in-place, but you can generate a new tuple with the desired value.
Given T = (4, 5, 6), you can change the first item by making a new tuple from its parts by slicing and concatenating: ``` T = (1,) + T[1:].
(Recall that single-item tuples require a trailing comma.) You ``` could also convert the tuple to a list, change it in-place, and convert it back to a tuple, but this is more expensive and is rarely required in practice—simply use a list if you know that the object will require in-place changes. 3.
The default for the processing mode argument in a file open call is 'r', for reading text input. For input text files, simply pass in the external file’s name. 4.
The pickle module can be used to store Python objects in a file without explicitly converting them to strings.
The struct module is related, but it assumes the data is to be in packed binary format in the file. 5.
Import the copy module, and call copy.deepcopy(X) if you need to copy all parts of a nested structure X.
This is also rarely seen in practice; references are usually the desired behavior, and shallow copies (e.g., aList[:], aDict.copy()) usually suffice for most copies. **|** ----- 6.
An object is considered true if it is either a nonzero number or a nonempty collection object.
The built-in words True and False are essentially predefined to have the same meanings as integer 1 and 0, respectively. 7.
Acceptable answers include “To learn Python,” “To move on to the next part of the book,” or “To seek the Holy Grail.” ###### Test Your Knowledge: Part II Exercises This session asks you to get your feet wet with built-in object fundamentals.
As before, a few new ideas may pop up along the way, so be sure to flip to the answers in Appendix B when you’re done (or when you’re not, if necessary).
If you have limited time, I suggest starting with exercises 10 and 11 (the most practical of the bunch), and then working from first to last as time allows.
This is all fundamental material, though, so try to do as many of these as you can. 1. The basics.
Experiment interactively with the common type operations found in the various operation tables in this part of the book.
To get started, bring up the Python interactive interpreter, type each of the following expressions, and try to explain what’s happening in each case.
Note that the semicolon in some of these is being used as a statement separator, to squeeze multiple statements onto a single line: for example, `X=1;X assigns and then prints a variable (more on statement` syntax in the next part of the book).
Also remember that a comma between expressions usually builds a tuple, even if there are no enclosing parentheses: X,Y,Z is a three-item tuple, which Python prints back to you in parentheses. ``` 2 ** 16 2 / 5, 2 / 5.0 "spam" + "eggs" S = "ham" "eggs " + S S * 5 S[:0] "green %s a...
Indexing and slicing. At the interactive prompt, define a list named L that contains four strings or numbers (e.g., L=[0,1,2,3]).
Then, experiment with some boundary cases; you may not ever see these cases in real programs, but they are intended to make you think about the underlying model, and some may be useful in less artificial forms: a.
What happens when you try to index out of bounds (e.g., L[4])? b. What about slicing out of bounds (e.g., L[−1000:100])? c.
Finally, how does Python handle it if you try to extract a sequence in reverse, with the lower bound greater than the higher bound (e.g., L[3:1])?
Hint: try assigning to this slice (L[3:1]=['?']), and see where the value is put. Do you think this may be the same phenomenon you saw when slicing out of bounds? 3. Indexing, slicing, and `del.
Define another list L with four items, and assign an empty` list to one of its offsets (e.g., L[2]=[]). What happens? Then, assign an empty list to a slice (L[2:3]=[]). What happens now?
Recall that slice assignment deletes the slice and inserts the new value where it used to be. The del statement deletes offsets, keys, attributes, and names.
Use it on your list to delete an item (e.g., `del L[0]). What happens if you delete an entire slice` (del L[1:])? What happens when you assign a nonsequence to a slice (L[1:2]=1)? 4. Tuple assignment.
Type the following lines: ``` >>> X = 'spam' >>> Y = 'eggs' >>> X, Y = Y, X ``` What do you think is happening to X and Y when you type this sequence? 5. Dictionary keys.
Consider the following code fragments: ``` >>> D = {} >>> D[1] = 'a' >>> D[2] = 'b' ``` You’ve learned that dictionaries aren’t accessed by offsets, so what’s going on here? Does the following shed any light on the subject?
(Hint: strings, integers, and tuples share which type category?) ``` >>> D[(1, 2, 3)] = 'c' >>> D {1: 'a', 2: 'b', (1, 2, 3): 'c'} ``` **|** ----- 6. Dictionary indexing.
Create a dictionary named D with three entries, for keys 'a', ``` 'b', and 'c'. What happens if you try to index a nonexistent key (D['d'])?
What ``` does Python do if you try to assign to a nonexistent key 'd' (e.g., D['d']='spam')? How does this compare to out-of-bounds assignments and references for lists? Does this sound like the rule for variable names? 7.
Generic operations. Run interactive tests to answer the following questions: a. What happens when you try to use the + operator on different/mixed types (e.g., string + list, list + tuple)? b.
Does + work when one of the operands is a dictionary? c. Does the append method work for both lists and strings? How about using the ``` keys method on lists?
(Hint: what does append assume about its subject object?) ``` d. Finally, what type of object do you get back when you slice or concatenate two lists or two strings? 8. String indexing.
Define a string `S of four characters:` `S = "spam". Then type the` following expression: S[0][0][0][0][0].
Any clue as to what’s happening this time? (Hint: recall that a string is a collection of characters, but Python characters are one-character strings.) Does this indexing expression still work if you apply it to a list such as ['s', 'p', 'a', 'm']?
Why? 9. Immutable types. Define a string S of four characters again: S = "spam".
Write an assignment that changes the string to "slam", using only slicing and concatenation. Could you perform the same operation using just indexing and concatenation? How about index assignment? 10.
Nesting. Write a data structure that represents your personal information: name (first, middle, last), age, job, address, email address, and phone number.
You may build the data structure with any combination of built-in object types you like (lists, tuples, dictionaries, strings, numbers).
Then, access the individual components of your data structures by indexing. Do some structures make more sense than others for this object? 11. Files.
Write a script that creates a new output file called myfile.txt and writes the string `"Hello file world!" into it. Then write another script that opens` _myfile.txt and reads and prints its contents.
Run your two scripts from the system_ command line. Does the new file show up in the directory where you ran your scripts?
What if you add a different directory path to the filename passed to open? Note: file write methods do not add newline characters to your strings; add an explicit \n at the end of the string if you want to fully terminate the line in the file. **|** ----- ----- ##### PART III ## Statements and Syntax ----- ----...
As in the previous part, we’ll begin here with a general introduction to statement syntax, and we’ll follow up with more details about specific statements in the next few chapters. In simple terms, statements are the things you write to tell Python what your programs should do.
If programs “do things with stuff,” statements are the way you specify what sort of things a program does.
Python is a procedural, statement-based language; by combining statements, you specify a procedure that Python performs to satisfy a program’s goals. ###### Python Program Structure Revisited Another way to understand the role of statements is to revisit the concept hierarchy introduced in Chapter 4, which talked abo...
This chapter climbs the hierarchy to the next level: 1. Programs are composed of modules. 2. Modules contain statements. 3. Statements contain expressions. 4.
Expressions create and process objects. At its core, Python syntax is composed of statements and expressions. Expressions process objects and are embedded in statements.
Statements code the larger logic of a program’s operation—they use and direct expressions to process the objects we studied in the preceding chapters.
Moreover, statements are where objects spring into existence (e.g., in expressions within assignment statements), and some statements create entirely new kinds of objects (functions, classes, and so on).
Statements always exist in modules, which themselves are managed with statements. ----- ###### Python’s Statements Table 10-1 summarizes Python’s statement set.
This part of the book deals with entries in the table from the top through break and continue.
You’ve informally been introduced to a few of the statements in Table 10-1 already; this part of the book will fill in details that were skipped earlier, introduce the rest of Python’s procedural statement set, and cover the overall syntax model.
Statements lower in Table 10-1 that have to do with larger program units—functions, classes, modules, and exceptions—lead to larger programming ideas, so they will each have a section of their own.
More focused statements (like del, which deletes various components) are covered elsewhere in the book, or in Python’s standard manuals. _Table 10-1.
Python 3.0 statements_ **Statement** **Role** **Example** Assignment Creating references `a, *b = 'good', 'bad', 'ugly'` Calls and other expressions Running functions `log.write("spam, ham")` `print calls` Printing objects `print('The Killer', joke)` `if/elif/else` Selecting actions `if "python" in text:` ``` ...
Here are a few fine points about its content: - Assignment statements come in a variety of syntax flavors, described in Chapter 11: basic, sequence, augmented, and more. - print is technically neither a reserved word nor a statement in 3.0, but a built-in function call; because it will nearly always be run as an ex...
As an expression, yield is also a reserved word, unlike print. Most of this table applies to Python 2.6, too, except where it doesn’t—if you are using Python 2.6 or older, here are a few notes for your Python, too: - In 2.6, nonlocal is not available; as we’ll see in Chapter 17, there are alternative ways to achieve...
Now, look at the equivalent statement in the Python language: ``` if x > y: x = 1 y = 2 ``` The first thing that may pop out at you is that the equivalent Python statement is less, well, cluttered—that is, there are fewer syntactic components.