Text
stringlengths
1
9.41k
It interprets the left argument much like a sprintf()style format string to be applied to the right argument, and returns the string resulting from this formatting operation.
For example: ----- More information can be found in the old-string-formatting section. ### 7.2 Reading and Writing Files ``` open() returns a file object, and is most commonly used with two arguments: open(filename, mode). >>> f = open('workfile', 'w') ``` The first argument is a string containing the filename.
The second argument is another string containing a few characters describing the way in which the file will be used.
mode can be 'r' when the file will only be read, 'w' for only writing (an existing file with the same name will be erased), and 'a' opens the file for appending; any data written to the file is automatically added to the end.
'r+' opens the file for both reading and writing.
The mode argument is optional; 'r' will be assumed if it’s omitted. Normally, files are opened in text mode, that means, you read and write strings from and to the file, which are encoded in a specific encoding.
If encoding is not specified, the default is platform dependent (see open()). ``` 'b' appended to the mode opens the file in binary mode: now the data is read and written in the form of ``` bytes objects.
This mode should be used for all files that don’t contain text. In text mode, the default when reading is to convert platform-specific line endings (\n on Unix, \r\n on Windows) to just \n.
When writing in text mode, the default is to convert occurrences of \n back to platform-specific line endings.
This behind-the-scenes modification to file data is fine for text files, but will corrupt binary data like that in JPEG or EXE files.
Be very careful to use binary mode when reading and writing such files. It is good practice to use the with keyword when dealing with file objects.
The advantage is that the file is properly closed after its suite finishes, even if an exception is raised at some point.
Using with is also much shorter than writing equivalent try-finally blocks: ``` >>> with open('workfile') as f: ...
read_data = f.read() >>> f.closed True ``` If you’re not using the with keyword, then you should call f.close() to close the file and immediately free up any system resources used by it.
If you don’t explicitly close a file, Python’s garbage collector will eventually destroy the object and close the open file for you, but the file may stay open for a while.
Another risk is that different Python implementations will do this clean-up at different times. After a file object is closed, either by a with statement or by calling f.close(), attempts to use the file object will automatically fail. ``` >>> f.close() >>> f.read() Traceback (most recent call last): File "<stdin>", ...
size is an optional numeric argument.
When size is omitted or negative, the entire contents of the file will be read and returned; it’s your problem if the file is twice as large as your machine’s memory.
Otherwise, at most size bytes are read and returned.
If the end of the file has been reached, f.read() will return an empty string (''). ``` >>> f.read() 'This is the entire file.\n' >>> f.read() '' f.readline() reads a single line from the file; a newline character (\n) is left at the end of the string, and ``` is only omitted on the last line of the file if the file d...
This makes the return value unambiguous; if f.readline() returns an empty string, the end of the file has been reached, while a blank line is represented by '\n', a string containing only a single newline. ``` >>> f.readline() 'This is the first line of the file.\n' >>> f.readline() 'Second line of the file\n' >>> f.re...
This is memory efficient, fast, and leads to simple code: ``` >>> for line in f: ...
print(line, end='') ... This is the first line of the file. Second line of the file ``` If you want to read all the lines of a file in a list you can also use list(f) or f.readlines(). ``` f.write(string) writes the contents of string to the file, returning the number of characters written. >>> f.write('This is a test...
The position is computed from adding offset to a reference point; the reference point is selected by the from_what argument.
A from_what value of 0 measures from the beginning of the file, 1 uses the current file position, and 2 uses the end of the file as the reference point.
from_what can be omitted and defaults to 0, using the beginning of the file as the reference point. ``` >>> f = open('workfile', 'rb+') >>> f.write(b'0123456789abcdef') ``` (continues on next page) ----- (continued from previous page) ``` 16 >>> f.seek(5) # Go to the 6th byte in the file 5 >>> f.read(1) b'5' >>> f....
Any other offset value produces undefined behaviour. File objects have some additional methods, such as isatty() and truncate() which are less frequently used; consult the Library Reference for a complete guide to file objects. #### 7.2.2 Saving structured data with json Strings can easily be written to and read fro...
Numbers take a bit more effort, since the read() method only returns strings, which will have to be passed to a function like int(), which takes a string like ``` '123' and returns its numeric value 123.
When you want to save more complex data types like nested lists ``` and dictionaries, parsing and serializing by hand becomes complicated. Rather than having users constantly writing and debugging code to save complicated data types to files, [Python allows you to use the popular data interchange format called JSON (...
Reconstructing the data from the string representation is called _deserializing.
Between serializing and deserializing, the string representing the object may have been stored_ in a file or data, or sent over a network connection to some distant machine. **Note:** The JSON format is commonly used by modern applications to allow for data exchange.
Many programmers are already familiar with it, which makes it a good choice for interoperability. If you have an object x, you can view its JSON string representation with a simple line of code: ``` >>> import json >>> json.dumps([1, 'simple', 'list']) '[1, "simple", "list"]' ``` Another variant of the dumps() functi...
So if f is a text file object opened for writing, we can do this: ``` json.dump(x, f) ``` To decode the object again, if f is a text file object which has been opened for reading: ``` x = json.load(f) ``` This simple serialization technique can handle lists and dictionaries, but serializing arbitrary class instances ...
The reference for the json module contains an explanation of this. **See also:** ``` pickle - the pickle module ``` ----- Contrary to JSON, pickle is a protocol which allows the serialization of arbitrarily complex Python objects. As such, it is specific to Python and cannot be used to communicate with applications...
It is also insecure by default: deserializing pickle data coming from an untrusted source can execute arbitrary code, if the data was crafted by a skilled attacker. ----- **CHAPTER** ### EIGHT ERRORS AND EXCEPTIONS Until now error messages haven’t been more than mentioned, but if you have tried out the examples ...
There are (at least) two distinguishable kinds of errors: syntax errors and exceptions. ### 8.1 Syntax Errors Syntax errors, also known as parsing errors, are perhaps the most common kind of complaint you get while you are still learning Python: ``` >>> while True print('Hello world') File "<stdin>", line 1 while ...
The error is caused by (or at least detected at) the token preceding the arrow: in the example, the error is detected at the function print(), since a colon (':') is missing before it.
File name and line number are printed so you know where to look in case the input came from a script. ### 8.2 Exceptions Even if a statement or expression is syntactically correct, it may cause an error when an attempt is made to execute it.
Errors detected during execution are called exceptions and are not unconditionally fatal: you will soon learn how to handle them in Python programs.
Most exceptions are not handled by programs, however, and result in error messages as shown here: ----- The last line of the error message indicates what happened.
Exceptions come in different types, and the type is printed as part of the message: the types in the example are ZeroDivisionError, NameError and ``` TypeError.
The string printed as the exception type is the name of the built-in exception that occurred. ``` This is true for all built-in exceptions, but need not be true for user-defined exceptions (although it is a useful convention).
Standard exception names are built-in identifiers (not reserved keywords). The rest of the line provides detail based on the type of exception and what caused it. The preceding part of the error message shows the context where the exception happened, in the form of a stack traceback.
In general it contains a stack traceback listing source lines; however, it will not display lines read from standard input. bltin-exceptions lists the built-in exceptions and their meanings. ### 8.3 Handling Exceptions It is possible to write programs that handle selected exceptions.
Look at the following example, which asks the user for input until a valid integer has been entered, but allows the user to interrupt the program (using ``` Control-C or whatever the operating system supports); note that a user-generated interruption is signalled ``` by raising the KeyboardInterrupt exception. ``` >>>...
try: ... x = int(input("Please enter a number: ")) ... break ... except ValueError: ... print("Oops! That was no valid number.
Try again...") ... ``` The try statement works as follows. - First, the try clause (the statement(s) between the try and except keywords) is executed. - If no exception occurs, the except clause is skipped and execution of the try statement is finished. - If an exception occurs during execution of the try cla...
Then if its type matches the exception named after the except keyword, the except clause is executed, and then execution continues after the try statement. - If an exception occurs which does not match the exception named in the except clause, it is passed on to outer try statements; if no handler is found, it is an...
At most one handler will be executed. Handlers only handle exceptions that occur in the corresponding try clause, not in other handlers of the same try statement.
An except clause may name multiple exceptions as a parenthesized tuple, for example: ``` ... except (RuntimeError, TypeError, NameError): ...
pass ``` A class in an except clause is compatible with an exception if it is the same class or a base class thereof (but not the other way around — an except clause listing a derived class is not compatible with a base class). For example, the following code will print B, C, D in that order: ``` class B(Exception): ...
Use this with extreme caution, since it is easy to mask a real programming error in this way!
It can also be used to print an error message and then re-raise the exception (allowing a caller to handle the exception as well): ``` import sys try: f = open('myfile.txt') s = f.readline() i = int(s.strip()) except OSError as err: print("OS error: {0}".format(err)) except ValueError: print("Could not conver...
For example: ``` for arg in sys.argv[1:]: try: f = open(arg, 'r') except OSError: print('cannot open', arg) else: print(arg, 'has', len(f.readlines()), 'lines') f.close() ``` The use of the else clause is better than adding additional code to the try clause because it avoids accidentally catching...
The presence and type of the argument depend on the exception type. The except clause may specify a variable after the exception name.
The variable is bound to an exception instance with the arguments stored in instance.args.
For convenience, the exception instance defines `__str__() so the arguments can be printed directly without having to reference .args.` One may also ----- instantiate an exception first before raising it and add any attributes to it as desired. ``` >>> try: ...
raise Exception('spam', 'eggs') ... except Exception as inst: ... print(type(inst)) # the exception instance ... print(inst.args) # arguments stored in .args ...
print(inst) # __str__ allows args to be printed directly, ... # but may be overridden in exception subclasses ... x, y = inst.args # unpack args ... print('x =', x) ...
print('y =', y) ... <class 'Exception'> ('spam', 'eggs') ('spam', 'eggs') x = spam y = eggs ``` If an exception has arguments, they are printed as the last part (‘detail’) of the message for unhandled exceptions. Exception handlers don’t just handle exceptions if they occur immediately in the try clause, but also if ...
For example: ``` >>> def this_fails(): ... x = 1/0 ... >>> try: ... this_fails() ... except ZeroDivisionError as err: ...
print('Handling run-time error:', err) ... Handling run-time error: division by zero ### 8.4 Raising Exceptions ``` The raise statement allows the programmer to force a specified exception to occur.
For example: ``` >>> raise NameError('HiThere') Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: HiThere ``` The sole argument to raise indicates the exception to be raised.
This must be either an exception instance or an exception class (a class that derives from Exception).
If an exception class is passed, it will be implicitly instantiated by calling its constructor with no arguments: ``` raise ValueError # shorthand for 'raise ValueError()' ``` If you need to determine whether an exception was raised but don’t intend to handle it, a simpler form of the raise statement allows you to re-...
raise NameError('HiThere') ... except NameError: ``` (continues on next page) ----- (continued from previous page) ``` ... print('An exception flew by!') ...
raise ... An exception flew by! Traceback (most recent call last): File "<stdin>", line 2, in <module> NameError: HiThere ### 8.5 User-defined Exceptions ``` Programs may name their own exceptions by creating a new exception class (see Classes for more about Python classes).
Exceptions should typically be derived from the Exception class, either directly or indirectly. Exception classes can be defined which do anything any other class can do, but are usually kept simple, often only offering a number of attributes that allow information about the error to be extracted by handlers for the e...
When creating a module that can raise several distinct errors, a common practice is to create a base class for exceptions defined by that module, and subclass that to create specific exception classes for different error conditions: ``` class Error(Exception): """Base class for exceptions in this module.""" pass cl...
For example: ``` >>> try: ... raise KeyboardInterrupt ... finally: ...
print('Goodbye, world!') ... Goodbye, world! KeyboardInterrupt Traceback (most recent call last): File "<stdin>", line 2, in <module> ``` A finally clause is always executed before leaving the try statement, whether an exception has occurred or not.
When an exception has occurred in the try clause and has not been handled by an except clause (or it has occurred in an except or else clause), it is re-raised after the finally clause has been executed.
The ``` finally clause is also executed “on the way out” when any other clause of the try statement is left via a break, continue or return statement.
A more complicated example: >>> def divide(x, y): ... try: ... result = x / y ... except ZeroDivisionError: ... print("division by zero!") ... else: ... print("result is", result) ... finally: ...
print("executing finally clause") ... >>> divide(2, 1) result is 2.0 executing finally clause >>> divide(2, 0) division by zero! executing finally clause >>> divide("2", "1") executing finally clause Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 3, in divide TypeError: un...
The TypeError raised by dividing two strings is not handled by the except clause and therefore re-raised after the finally clause has been executed. In real world applications, the finally clause is useful for releasing external resources (such as files or network connections), regardless of whether the use of the res...
Look at the following example, which tries to open a file and print its contents to the screen. ----- The problem with this code is that it leaves the file open for an indeterminate amount of time after this part of the code has finished executing.
This is not an issue in simple scripts, but can be a problem for larger applications.
The with statement allows objects like files to be used in a way that ensures they are always cleaned up promptly and correctly. ``` with open("myfile.txt") as f: for line in f: print(line, end="") ``` After the statement is executed, the file f is always closed, even if a problem was encountered while processin...
Objects which, like files, provide predefined clean-up actions will indicate this in their documentation. ----- ----- **CHAPTER** ### NINE CLASSES Classes provide a means of bundling data and functionality together.
Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to it for maintaining its state.
Class instances can also have methods (defined by its class) for modifying its state. Compared with other programming languages, Python’s class mechanism adds classes with a minimum of new syntax and semantics.
It is a mixture of the class mechanisms found in C++ and Modula-3.
Python classes provide all the standard features of Object Oriented Programming: the class inheritance mechanism allows multiple base classes, a derived class can override any methods of its base class or classes, and a method can call the method of a base class with the same name.
Objects can contain arbitrary amounts and kinds of data.
As is true for modules, classes partake of the dynamic nature of Python: they are created at runtime, and can be modified further after creation. In C++ terminology, normally class members (including the data members) are public (except see below _Private Variables), and all member functions are virtual._ As in Modula...
As in Smalltalk, classes themselves are objects. This provides semantics for importing and renaming. Unlike C++ and Modula-3, built-in types can be used as base classes for extension by the user.
Also, like in C++, most built-in operators with special syntax (arithmetic operators, subscripting etc.) can be redefined for class instances. (Lacking universally accepted terminology to talk about classes, I will make occasional use of Smalltalk and C++ terms.
I would use Modula-3 terms, since its object-oriented semantics are closer to those of Python than C++, but I expect that few readers have heard of it.) ### 9.1 A Word About Names and Objects Objects have individuality, and multiple names (in multiple scopes) can be bound to the same object.
This is known as aliasing in other languages. This is usually not appreciated on a first glance at Python, and can be safely ignored when dealing with immutable basic types (numbers, strings, tuples).
However, aliasing has a possibly surprising effect on the semantics of Python code involving mutable objects such as lists, dictionaries, and most other types.
This is usually used to the benefit of the program, since aliases behave like pointers in some respects.
For example, passing an object is cheap since only a pointer is passed by the implementation; and if a function modifies an object passed as an argument, the caller will see the change — this eliminates the need for two different argument passing mechanisms as in Pascal. ### 9.2 Python Scopes and Namespaces Before in...
Class definitions play some neat tricks with namespaces, and you need to know how scopes and namespaces work to fully ----- understand what’s going on.
Incidentally, knowledge about this subject is useful for any advanced Python programmer. Let’s begin with some definitions. A namespace is a mapping from names to objects.
Most namespaces are currently implemented as Python dictionaries, but that’s normally not noticeable in any way (except for performance), and it may change in the future.
Examples of namespaces are: the set of built-in names (containing functions such as abs(), and built-in exception names); the global names in a module; and the local names in a function invocation. In a sense the set of attributes of an object also form a namespace.
The important thing to know about namespaces is that there is absolutely no relation between names in different namespaces; for instance, two different modules may both define a function maximize without confusion — users of the modules must prefix it with the module name. By the way, I use the word attribute for any ...
Strictly speaking, references to names in modules are attribute ``` references: in the expression modname.funcname, modname is a module object and funcname is an attribute of it.
In this case there happens to be a straightforward mapping between the module’s attributes and the global names defined in the module: they share the same namespace![1] Attributes may be read-only or writable.