Text
stringlengths
1
9.41k
These don’t quite map to the Python object model because Python has no notion of in-place changes to immutable objects like numbers. **|** ----- And to add a set of items to the end, we can either concatenate again or call the list ``` extend method:[†] ``` `>>> L = L + [5, 6]` _# Concatenate: slower_ ``` >>> L ...
Concatenation operations must create a new object, copy in the list on the left, and then copy in the list on the right.
By contrast, in-place method calls simply add items at the end of a memory block. When we use augmented assignment to extend a list, we can forget these details—for example, Python automatically calls the quicker extend method instead of using the slower concatenation operation implied by +: `>>> L += [9, 10]` _# Map...
As for all shared reference cases, this difference might matter if other names reference the object being changed: ``` >>> L = [1, 2] ``` `>>> M = L` _# L and M reference the same object_ `>>> L = L + [3, 4]` _# Concatenation makes a new object_ `>>> L, M` _# Changes L but not M_ ``` ([1, 2, 3, 4], [1, 2]) >>> L...
As always, make copies of your mutable objects if you need to break the shared reference structure. † As suggested in Chapter 6, we can also use slice assignment (e.g., L[len(L):] = [11,12,13]), but this works roughly the same as the simpler list extend method. **|** ----- ###### Variable Name Rules Now that we’v...
In Python, names come into existence when you assign values to them, but there are a few rules to follow when picking names for things in your programs: _Syntax: (underscore or letter) + (any number of letters, digits, or underscores)_ Variable names must start with an underscore or letter, which can be followed by an...
`_spam,` `spam, and` `Spam_1 are legal` names, but 1_Spam, spam$, and @#!
are not. _Case matters: SPAM is not the same as spam_ Python always pays attention to case in programs, both in names you create and in reserved words.
For instance, the names X and x refer to two different variables. For portability, case also matters in the names of imported module files, even on platforms where the filesystems are case-insensitive. _Reserved words are off-limits_ Names you define cannot be the same as words that mean special things in the Python la...
For instance, if you try to use a variable name like class, Python will raise a syntax error, but klass and Class work fine.
Table 11-3 lists the words that are currently reserved (and hence off-limits for names of your own) in Python. _Table 11-3.
Python 3.0 reserved words_ ``` False class finally is return None continue for lambda try True def from nonlocal while and del global not with as elif if or yield assert else import pass break except in raise ``` Table 11-3 is specific to Python 3.0.
In Python 2.6, the set of reserved words differs slightly: - print is a reserved word, because printing is a statement, not a built-in (more on this later in this chapter). - exec is a reserved word, because it is a statement, not a built-in function. - nonlocal is not a reserved word because this statement is no...
They are also all truly reserved—unlike names in the built-in scope that you will meet in the next part of this book, you cannot redefine reserved words by assignment (e.g., and = 1 results in a syntax error).[‡] Besides being of mixed case, the first three entries in Table 11-3, `True,` `False, and` ``` None, are som...
All the other reserved words are hardwired into Python’s syntax and can appear only in the specific contexts for which they are intended. Furthermore, because module names in import statements become variables in your scripts, variable name constraints extend to your module filenames too.
For instance, you can code files called and.py and my-code.py and run them as top-level scripts, but you cannot import them: their names without the “.py” extension become variables in your code and so must follow all the variable rules just outlined.
Reserved words are off-limits, and dashes won’t work, though underscores will.
We’ll revisit this idea in Part V of this book. ###### Python’s Deprecation Protocol It is interesting to note how reserved word changes are gradually phased into the language.
When a new feature might break existing code, Python normally makes it an option and begins issuing “deprecation” warnings one or more releases before the feature is officially enabled.
The idea is that you should have ample time to notice the warnings and update your code before migrating to the new release.
This is not true for major new releases like 3.0 (which breaks existing code freely), but it is generally true in other cases. For example, yield was an optional extension in Python 2.2, but is a standard keyword as of 2.3.
It is used in conjunction with generator functions. This was one of a small handful of instances where Python broke with backward compatibility.
Still, yield was phased in over time: it began generating deprecation warnings in 2.2 and was not enabled until 2.3. ‡ In the Jython Java-based implementation of Python, though, user-defined variable names can sometimes be the same as Python reserved words.
See Chapter 2 for an overview of the Jython system. **|** ----- ###### Naming conventions Besides these rules, there is also a set of naming conventions—rules that are not required but are followed in normal practice.
For instance, because names with two leading and trailing underscores (e.g., __name__) generally have special meaning to the Python interpreter, you should avoid this pattern for your own names.
Here is a list of the conventions Python follows: - Names that begin with a single underscore (_X) are not imported by a from module ``` import * statement (described in Chapter 22). ``` - Names that have two leading and trailing underscores (__X__) are system-defined names that have special meaning to the interp...
For instance, later in the book we’ll see that class names commonly start with an uppercase letter and module names with a lowercase letter, and that the name self, though not reserved, usually has a special role in classes.
In Chapter 17 we’ll also study another, larger category of names known as the _built-ins, which are predefined but not reserved (and so can be reassigned: open = 42_ works, though sometimes you might wish it didn’t!). ###### Names have no type, but objects do This is mostly review, but remember that it’s crucial to k...
As described in Chapter 6, objects have a type (e.g., integer, list) and may be mutable or not. Names (a.k.a.
variables), on the other hand, are always just references to objects; they have no notion of mutability and have no associated type information, apart from the type of the object they happen to reference at a given point in time. **|** ----- Thus, it’s OK to assign the same name to different kinds of objects at dif...
In Chapter 17, you’ll also learn that names also live in something called a scope, which defines where they can be used; the place where you assign a name determines where it is visible.[§] For additional naming suggestions, see the previous section “Naming conventions” of Python’s semi-official style guide, known as ...
This guide is available at http://www.python.org/dev/peps/pep-0008, or via a web search for “Python PEP 8.” Technically, this document formalizes coding standards for Python library code. Though useful, the usual caveats about coding standards apply here. For one thing, PEP 8 comes with more detail than you are probab...
And frankly, it has become more complex, rigid, and subjective than it needs to be—some of its suggestions are not at all universally accepted or followed by Python programmers doing real work.
Moreover, some of the most prominent companies using Python today have adopted coding standards of their own that differ. PEP 8 does codify useful rule-of-thumb Python knowledge, though, and it’s a great read for Python beginners, as long as you take its recommendations as guidelines, not gospel. ###### Expression St...
Expressions are commonly used as statements in two situations: _For calls to functions and methods_ Some functions and methods do lots of work without returning a value.
Such functions are sometimes called procedures in other languages.
Because they don’t return values that you might be interested in retaining, you can call these functions with expression statements. § If you’ve used a more restrictive language like C++, you may be interested to know that there is no notion of C++’s const declaration in Python; certain objects may be immutable, but n...
Technically, these are expression statements, too; they serve as a shorthand for typing print statements. Table 11-4 lists some common expression statement forms in Python.
Calls to functions and methods are coded with zero or more argument objects (really, expressions that evaluate to objects) in parentheses, after the function/method name. _Table 11-4.
Common Python expression statements_ **Operation** **Interpretation** `spam(eggs, ham)` Function calls `spam.ham(eggs)` Method calls `spam` Printing variables in the interactive interpreter `print(a, b, c, sep='')` Printing operations in Python 3.0 `yield x ** 2` Yielding expression statements The last two ent...
Both are really just instances of expression statements. For instance, though you normally run a print call on a line by itself as an expression statement, it returns a value like any other function call (its return value is None, the default return value for functions that don’t return anything meaningful): `>>> x =...
For example, Python doesn’t allow you to embed assignment statements (=) in other expressions.
The rationale for this is that it avoids common coding mistakes; you can’t accidentally change a variable by typing = when you really mean to use the == equality test.
You’ll see how to code around this when you meet the Python while loop in Chapter 13. ###### Expression Statements and In-Place Changes This brings up a mistake that is common in Python work.
Expression statements are often used to run list methods that change a list in-place: ``` >>> L = [1, 2] ``` `>>> L.append(3)` _# Append is an in-place change_ ``` >>> L [1, 2, 3] ``` **|** ----- However, it’s not unusual for Python newcomers to code such an operation as an assignment statement instead, inte...
Calling an in-place change operation such as append, ``` sort, or reverse on a list always changes the list in-place, but these methods do not ``` return the list they have changed; instead, they return the `None object.
Thus, if you` assign such an operation’s result back to the variable name, you effectively lose the list (and it is probably garbage collected in the process!). The moral of the story is, don’t do this.
We’ll revisit this phenomenon in the section “Common Coding Gotchas” on page 387 at the end of this part of the book because it can also appear in the context of some looping statements we’ll meet in later chapters. ###### Print Operations In Python, `print prints things—it’s simply a programmer-friendly interface to...
In a bit more detail, print is strongly bound up with the notions of files and streams in Python: _File object methods_ In Chapter 9, we learned about file object methods that write text (e.g., ``` file.write(str)).
Printing operations are similar, but more focused—whereas file ``` write methods write strings to arbitrary files, `print writes objects to the` `stdout` stream by default, with some automatic formatting added.
Unlike with file methods, there is no need to convert objects to strings when using print operations. _Standard output stream_ The standard output stream (often known as stdout) is simply a default place to send a program’s text output.
Along with the standard input and error streams, it’s one of three data connections created when your script starts.
The standard output stream is usually mapped to the window where you started your Python program, unless it’s been redirected to a file or pipe in your operating system’s shell. Because the standard output stream is available in Python as the stdout file object in the built-in sys module (i.e., sys.stdout), it’s possib...
However, print is noticeably easier to use and makes it easy to print text to other files and streams. **|** ----- Printing is also one of the most visible places where Python 3.0 and 2.6 have diverged. In fact, this divergence is usually the first reason that most 2.X code won’t run unchanged under 3.X.
Specifically, the way you code print operations depends on which version of Python you use: - In Python 3.X, printing is a built-in function, with keyword arguments for special modes. - In Python 2.X, printing is a statement with specific syntax all its own. Because this book covers both 3.0 and 2.6, we will look ...
If you are fortunate enough to be able to work with code written for just one version of Python, feel free to pick the section that is relevant to you; however, as your circumstances may change, it probably won’t hurt to be familiar with both cases. ###### The Python 3.0 print Function Strictly speaking, printing is ...
Instead, it is simply an instance of the expression statement we studied in the preceding section. The print built-in function is normally called on a line of its own, because it doesn’t return any value we care about (technically, it returns `None).
Because it is a normal` function, though, printing in 3.0 uses standard function-call syntax, rather than a special statement form.
Because it provides special operation modes with keyword arguments, this form is both more general and supports future enhancements better. By comparison, Python 2.6 print statements have somewhat ad-hoc syntax to support extensions such as end-of-line suppression and target files.
Further, the 2.6 statement does not support separator specification at all; in 2.6, you wind up building strings ahead of time more often than you do in 3.0. ###### Call format Syntactically, calls to the 3.0 print function have the following form: ``` print([object, ...][, sep=' '][, end='\n'][, file=sys.stdout]) ...
In English, this built-in function prints the textual representation of one or more objects separated by the string sep and followed by the string end to the stream file. The sep, end, and file parts, if present, must be given as keyword arguments—that is, you must use a special “name=value” syntax to pass the argumen...
Keyword arguments are covered in depth in Chapter 18, but they’re straightforward to use.
The keyword arguments sent to this call may appear in any left-to-right order following the objects to be printed, and they control the print operation: **|** ----- - sep is a string inserted between each object’s text, which defaults to a single space if not passed; passing an empty string suppresses separators a...
Passing an empty string avoids dropping down to the next output line at the end of the printed text—the next print will keep adding to the end of the current output line. - file specifies the file, standard stream, or other file-like object to which the text will be sent; it defaults to the sys.stdout standard output...
Any object with a file-like write(string) method may be passed, but real files should be already opened for output. The textual representation of each object to be printed is obtained by passing the object to the str built-in call; as we’ve seen, this built-in returns a “user friendly” display string for any object.[‖...
To illustrate, let’s run some quick examples.
The following prints a variety of object types to the default standard output stream, with the default separator and end-of-line formatting added (these are the defaults because they are the most common use case): ``` C:\misc> c:\python30\python >>> ``` `>>> print()` _# Display a blank line_ ``` >>> x = 'spam' ...
By default, print calls add a space between the objects printed.
To suppress this, send an empty string to the sep keyword argument, or send an alternative separator of your choosing: `>>> print(x, y, z, sep='')` _# Suppress separator_ ``` spam99['eggs'] >>> ``` `>>> print(x, y, z, sep=', ')` _# Custom separator_ ``` spam, 99, ['eggs'] ``` ‖ Technically, printing uses the e...
Besides this to-string conversion role, str is also the name of the string data type and can be used to decode Unicode strings from raw bytes with an extra encoding argument, as we’ll learn in Chapter 36; this latter role is an advanced usage that we can safely ignore here. **|** ----- Also by default, print adds a...
You can suppress this and avoid the line break altogether by passing an empty string to the ``` end keyword argument, or you can pass a different terminator of your own (include a \n character to break the line manually): ``` `>>> print(x, y, z, end='')` _# Suppress line break_ ``` spam 99 ['eggs']>>> >>> ``` `>>...
If you need to display more specific formatting, don’t print this way, Instead, build up a more complex string ahead of time or within the ``` print itself using the string tools we met in Chapter 7, and print the string all at once: >>> text = '%s: %-.4f, %05d' % ('Result', 3.14159, 42) >>> print(text) Result: 3...
In practice, though, 2.6 printing is mostly a variation on a theme; with the exception of separator strings (which are supported in **|** ----- 3.0 but not 2.6), everything we can do with the 3.0 print function has a direct translation to the 2.6 print statement. ###### Statement forms Table 11-5 lists the print ...
Notice that the` _comma is significant in_ ``` print statements—it separates objects to be printed, and a trailing comma suppresses ``` the end-of-line character normally added at the end of the printed text (not to be confused with tuple syntax!).
The >> syntax, normally used as a bitwise right-shift operation, is used here as well, to specify a target output stream other than the sys.stdout default. _Table 11-5.
Python 2.6 print statement forms_ **Python 2.6 statement** **Python 3.0 equivalent** **Interpretation** `print x, y` `print(x, y)` Print objects’ textual forms to sys.stdout; add a space between the items and an end-of-line at the end `print x, y,` `print(x, y, end='')` Same, but don’t add end-of-line at end of te...
Let’s turn to some basic examples again.
By default, the 2.6 ``` print statement adds a space between the items separated by commas and adds a line ``` break at the end of the current output line: ``` C:\misc> c:\python26\python >>> >>> x = 'a' >>> y = 'b' >>> print x, y a b ``` This formatting is just a default; you can choose to use it or not.
To suppress the line break so you can add more text to the current line later, end your print statement with a comma, as shown in the second line of Table 11-5 (the following is two statements on one line, separated by a semicolon): ``` >>> print x, y,; print x, y a b a b ``` **|** ----- To suppress the space b...
Instead, build up an output string using the string concatenation and formatting tools covered in Chapter 7, and print the string all at once: ``` >>> print x + y ab >>> print '%s...%s' % (x, y) a...b ``` As you can see, apart from their special syntax for usage modes, 2.6 print statements are roughly as simpl...
The next section uncovers the way that files are specified in 2.6 prints. ###### Print Stream Redirection In both Python 3.0 and 2.6, printing sends text to the standard output stream by default. However, it’s often useful to send it elsewhere—to a text file, for example, to save results for later use or testing purp...
Although such redirection can be accomplished in system shells outside Python itself, it turns out to be just as easy to redirect a script’s streams from within the script. ###### The Python “hello world” program Let’s start off with the usual (and largely pointless) language benchmark—the “hello world” program.
To print a “hello world” message in Python, simply print the string per your version’s print operation: `>>> print('hello world')` _# Print a string object in 3.0_ ``` hello world ``` `>>> print 'hello world'` _# Print a string object in 2.6_ ``` hello world ``` Because expression results are echoed on the inter...
Really, the print operation is just an ergonomic feature of Python—it provides a simple interface to the sys.stdout object, with a bit of default formatting.
In fact, if you enjoy working harder than you must, you can also code print operations this way: `>>> import sys` _# Printing the hard way_ ``` >>> sys.stdout.write('hello world\n') hello world ``` **|** ----- This code explicitly calls the write method of sys.stdout—an attribute preset when Python starts up t...
The `print` operation hides most of those details, providing a simple tool for simple printing tasks. ###### Manual stream redirection So, why did I just show you the hard way to print?
The sys.stdout print equivalent turns out to be the basis of a common technique in Python. In general, `print and` ``` sys.stdout are directly related as follows.
This statement: print(X, Y) # Or, in 2.6: print X, Y ``` is equivalent to the longer: ``` import sys sys.stdout.write(str(X) + ' ' + str(Y) + '\n') ``` which manually performs a string conversion with str, adds a separator and newline with +, and calls the output stream’s write method.
Which would you rather code? (He says, hoping to underscore the programmer-friendly nature of prints....) Obviously, the long form isn’t all that useful for printing by itself.
However, it is useful to know that this is exactly what print operations do because it is possible to reas_sign_ `sys.stdout to something different from the standard output stream.
In other words,` this equivalence provides a way of making your print operations send their text to other places.
For example: ``` import sys sys.stdout = open('log.txt', 'a') # Redirects prints to a file ... print(x, y, x) # Shows up in log.txt ``` Here, we reset sys.stdout to a manually opened file named log.txt, located in the script’s working directory and opened in append mode (so we add to its current...
After the reset, every print operation anywhere in the program will write its text to the end of the file log.txt instead of to the original output stream.
The `print operations are` happy to keep calling sys.stdout’s write method, no matter what sys.stdout happens to refer to.
Because there is just one `sys module in your process, assigning` ``` sys.stdout this way will redirect every print anywhere in your program. ``` In fact, as this chapter’s upcoming sidebar about print and stdout will explain, you can even reset sys.stdout to an object that isn’t a file at all, as long as it has the e...
When that object is a class, printed text can be routed and processed arbitrarily per a write method you code yourself. This trick of resetting the output stream is primarily useful for programs originally coded with print statements.
If you know that output should go to a file to begin with, you can always call file write methods instead.
To redirect the output of a print-based **|** ----- program, though, resetting sys.stdout provides a convenient alternative to changing every print statement or using system shell-based redirection syntax. ###### Automatic stream redirection This technique of redirecting printed text by assigning sys.stdout is co...
One potential problem with the last section’s code, though, is that there is no direct way to restore the original output stream should you need to switch back after printing to a file.
Because sys.stdout is just a normal file object, you can always save it and restore it if needed:[#] ``` C:\misc> c:\python30\python >>> import sys ``` `>>> temp = sys.stdout` _# Save for restoring later_ `>>> sys.stdout = open('log.txt', 'a')` _# Redirect prints to a file_ `>>> print('spam')` _# Prints go to file...