From 4302e3613dad43738f3cf98a4ed0d95416d98e09 Mon Sep 17 00:00:00 2001 From: Mark Pilgrim Date: Tue, 14 Jul 2009 00:07:18 -0400 Subject: [PATCH] added section on exceptions to your-first-python-program --- dip2 | 115 ++++----------------------------- examples/humansize.py | 0 xml.html | 0 your-first-python-program.html | 89 ++++++++++++++++++++++--- 4 files changed, 93 insertions(+), 111 deletions(-) mode change 100644 => 100755 dip2 mode change 100644 => 100755 examples/humansize.py mode change 100644 => 100755 xml.html mode change 100644 => 100755 your-first-python-program.html diff --git a/dip2 b/dip2 old mode 100644 new mode 100755 index 9e7277d..04a1450 --- a/dip2 +++ b/dip2 @@ -385,15 +385,18 @@ if __name__ == "__main__": NoteWhen a command is split among several lines with the line-continuation marker (“\”), the continued lines can be indented in any manner; Python's normally stringent indentation rules do not apply. If your Python IDE auto-indents the continued line, you should probably accept its default unless you have a burning reason not to.

Strictly speaking, expressions in parentheses, straight brackets, or curly braces (like defining a dictionary) can be split into multiple lines with or without the line continuation character (“\”). I like to include the backslash even when it's not required because I think it makes the code easier to read, but that's a matter of style. -

Third, you never declared the variable myParams, you just assigned a value to it. This is like VBScript without the option explicit option. Luckily, unlike VBScript, Python will not allow you to reference a variable that has never been assigned a value; trying to do so will raise an exception. -

3.4.1. Referencing Variables

-

Example 3.18. Referencing an Unbound Variable

>>> x
-Traceback (innermost last):
-  File "<interactive input>", line 1, in ?
-NameError: There is no variable named 'x'
->>> x = 1
->>> x
-1

You will thank Python for this one day. + + + + + +[unbound variable exception example was here] + + + + + +

3.4.2. Assigning Multiple Values at Once

One of the cooler programming shortcuts in Python is using sequences to assign multiple values at once.

Example 3.19. Assigning multiple values at once

>>> v = ('a', 'b', 'e')
@@ -1604,104 +1607,12 @@ AttributeError: 'MP3FileInfo' instance has no attribute '__parse'
  • Defining private attributes and methods
    -

    Chapter 6. Exceptions and File Handling

    -

    In this chapter, you will dive into exceptions, file objects, for loops, and the os and sys modules. If you've used exceptions in another programming language, you can skim the first section to get a sense of Python's syntax. Be sure to tune in again for file handling. -

    6.1. Handling Exceptions

    -

    Like many other programming languages, Python has exception handling via try...except blocks. - -
    NotePython uses try...except to handle exceptions and raise to generate them. Java and C++ use try...catch to handle exceptions, and throw to generate them. -

    Exceptions are everywhere in Python. Virtually every module in the standard Python library uses them, and Python itself will raise them in a lot of different circumstances. You've already seen them repeatedly throughout this book. -

    - -

    In each of these cases, you were simply playing around in the Python IDE: an error occurred, the exception was printed (depending on your IDE, perhaps in an intentionally jarring shade of red), and that was that. This is called an unhandled exception. When the exception was raised, there was no code to explicitly notice it and deal with it, so it bubbled its -way back to the default behavior built in to Python, which is to spit out some debugging information and give up. In the IDE, that's no big deal, but if that happened while your actual Python program was running, the entire program would come to a screeching halt. -

    An exception doesn't need result in a complete program crash, though. Exceptions, when raised, can be handled. Sometimes an exception is really because you have a bug in your code (like accessing a variable that doesn't exist), but -many times, an exception is something you can anticipate. If you're opening a file, it might not exist. If you're connecting -to a database, it might be unavailable, or you might not have the correct security credentials to access it. If you know -a line of code may raise an exception, you should handle the exception using a try...except block. -

    Example 6.1. Opening a Non-Existent File

    >>> fsock = open("/notthere", "r")      
    -Traceback (innermost last):
    -  File "<interactive input>", line 1, in ?
    -IOError: [Errno 2] No such file or directory: '/notthere'
    ->>> try:
    -...    fsock = open("/notthere")       
    -... except IOError:   
    -...    print "The file does not exist, exiting gracefully"
    -... print "This line will always print" 
    -The file does not exist, exiting gracefully
    -This line will always print
    -
      -
    1. Using the built-in open function, you can try to open a file for reading (more on open in the next section). But the file doesn't exist, so this raises the IOError exception. Since you haven't provided any explicit check for an IOError exception, Python just prints out some debugging information about what happened and then gives up. -
    2. You're trying to open the same non-existent file, but this time you're doing it within a try...except block. -
    3. When the open method raises an IOError exception, you're ready for it. The except IOError: line catches the exception and executes your own block of code, which in this case just prints a more pleasant error message. -
    4. Once an exception has been handled, processing continues normally on the first line after the try...except block. Note that this line will always print, whether or not an exception occurs. If you really did have a file called -notthere in your root directory, the call to open would succeed, the except clause would be ignored, and this line would still be executed. -

      Exceptions may seem unfriendly (after all, if you don't catch the exception, your entire program will crash), but consider -the alternative. Would you rather get back an unusable file object to a non-existent file? You'd need to check its validity -somehow anyway, and if you forgot, somewhere down the line, your program would give you strange errors somewhere down the -line that you would need to trace back to the source. I'm sure you've experienced this, and you know it's not fun. With -exceptions, errors occur immediately, and you can handle them in a standard way at the source of the problem. -

      6.1.1. Using Exceptions For Other Purposes

      -

      There are a lot of other uses for exceptions besides handling actual error conditions. A common use in the standard Python library is to try to import a module, and then check whether it worked. Importing a module that does not exist will raise - an ImportError exception. You can use this to define multiple levels of functionality based on which modules are available at run-time, - or to support multiple platforms (where platform-specific code is separated into different modules). -

      You can also define your own exceptions by creating a class that inherits from the built-in Exception class, and then raise your exceptions with the raise command. See the further reading section if you're interested in doing this. -

      The next example demonstrates how to use an exception to support platform-specific functionality. This code comes from the -getpass module, a wrapper module for getting a password from the user. Getting a password is accomplished differently on UNIX, Windows, and Mac OS platforms, but this code encapsulates all of those differences. -

      Example 6.2. Supporting Platform-Specific Functionality

      
      -  # Bind the name getpass to the appropriate function
      -  try:
      -      import termios, TERMIOS   
      -  except ImportError:
      -      try:
      -          import msvcrt         
      -      except ImportError:
      -          try:
      -              from EasyDialogs import AskPassword 
      -          except ImportError:
      -              getpass = default_getpass           
      -          else:                 
      -              getpass = AskPassword
      -      else:
      -          getpass = win_getpass
      -  else:
      -      getpass = unix_getpass
      -
        -
      1. termios is a UNIX-specific module that provides low-level control over the input terminal. If this module is not available (because it's not - on your system, or your system doesn't support it), the import fails and Python raises an ImportError, which you catch. -
      2. OK, you didn't have termios, so let's try msvcrt, which is a Windows-specific module that provides an API to many useful functions in the Microsoft Visual C++ runtime services. If this import fails, Python will raise an ImportError, which you catch. -
      3. If the first two didn't work, you try to import a function from EasyDialogs, which is a Mac OS-specific module that provides functions to pop up dialog boxes of various types. Once again, if this import fails, Python will raise an ImportError, which you catch. -
      4. None of these platform-specific modules is available (which is possible, since Python has been ported to a lot of different platforms), so you need to fall back on a default password input function (which is - defined elsewhere in the getpass module). Notice what you're doing here: assigning the function default_getpass to the variable getpass. If you read the official getpass documentation, it tells you that the getpass module defines a getpass function. It does this by binding getpass to the correct function for your platform. Then when you call the getpass function, you're really calling a platform-specific function that this code has set up for you. You don't need to know or - care which platform your code is running on -- just call getpass, and it will always do the right thing. -
      5. A try...except block can have an else clause, like an if statement. If no exception is raised during the try block, the else clause is executed afterwards. In this case, that means that the from EasyDialogs import AskPassword import worked, so you should bind getpass to the AskPassword function. Each of the other try...except blocks has similar else clauses to bind getpass to the appropriate function when you find an import that works. -
        -

        Further Reading on Exception Handling

        - +[exception stuff was here] diff --git a/examples/humansize.py b/examples/humansize.py old mode 100644 new mode 100755 diff --git a/xml.html b/xml.html old mode 100644 new mode 100755 diff --git a/your-first-python-program.html b/your-first-python-program.html old mode 100644 new mode 100755 index aba01bb..2ef8e07 --- a/your-first-python-program.html +++ b/your-first-python-program.html @@ -9,6 +9,7 @@ body{counter-reset:h1 1} table{border:1px solid #bbb;border-collapse:collapse;margin:auto} td,th{border:1px solid #bbb;padding:0 1.75em} th{text-align:left} +mark{display:inline} @@ -54,12 +55,12 @@ if __name__ == '__main__': print(approximate_size(1000000000000, False)) print(approximate_size(1000000000000))

        Now let’s run this program on the command line. On Windows, it will look something like this: -

        +
         c:\home\diveintopython3> c:\python30\python.exe humansize.py
         1.0 TB
         931.3 GiB

        On Mac OS X or Linux, it would look something like this: -

        +
         you@localhost:~$ python3 humansize.py
         1.0 TB
         931.3 GiB
        @@ -74,7 +75,7 @@ if __name__ == '__main__':

        Declaring Functions

        Python has functions like most other languages, but it does not have separate header files like C++ or interface/implementation sections like Pascal. When you need a function, just declare it, like this: -

        def approximate_size(size, a_kilobyte_is_1024_bytes=True):
        +
        def approximate_size(size, a_kilobyte_is_1024_bytes=True):

        The keyword def starts the function declaration, followed by the function name, followed by the arguments in parentheses. Multiple arguments are separated with commas.

        Also note that the function doesn’t define a return datatype. Python functions do not specify the datatype of their return value; they don’t even specify whether or not they return a value. (In fact, every Python function returns a value; if the function ever executes a return statement, it will return that value, otherwise it will return None, the Python null value.) @@ -92,7 +93,7 @@ if __name__ == '__main__':

        Let’s take another look at that approximate_size() function declaration: -

        def approximate_size(size, a_kilobyte_is_1024_bytes=True):
        +
        def approximate_size(size, a_kilobyte_is_1024_bytes=True):

        The second argument, a_kilobyte_is_1024_bytes, specifies a default value of True. This means the argument is optional; you can call the function without it, and Python will act as if you had called it with True as a second parameter. @@ -177,7 +178,7 @@ SyntaxError: non-keyword arg after keyword arg

          -
        1. The first line imports the humansize program as a module -- a chunk of code that you can use interactively, or from a larger Python program. (You’ll see examples of multi-module Python programs in [FIXME xref].) Once you import a module, you can reference any of its public functions, classes, or attributes. Modules can do this to access functionality in other modules, and you can do it in the Python interactive shell too. This is an important concept, and you’ll see a lot more of it throughout this book. +
        2. The first line imports the humansize program as a module — a chunk of code that you can use interactively, or from a larger Python program. (You’ll see examples of multi-module Python programs in [FIXME xref].) Once you import a module, you can reference any of its public functions, classes, or attributes. Modules can do this to access functionality in other modules, and you can do it in the Python interactive shell too. This is an important concept, and you’ll see a lot more of it throughout this book.
        3. When you want to use functions defined in imported modules, you need to include the module name. So you can’t just say approximate_size; it must be humansize.approximate_size. If you’ve used classes in Java, this should feel vaguely familiar.
        4. Instead of calling the function as you would expect to, you asked for one of the function’s attributes, __doc__.
        @@ -237,7 +238,7 @@ SyntaxError: non-keyword arg after keyword arg raise ValueError('number too large')
        1. Code blocks are defined by their indentation. By “code block,” I mean functions, if statements, for loops, while loops, and so forth. Indenting starts a block and unindenting ends it. There are no explicit braces, brackets, or keywords. This means that whitespace is significant, and must be consistent. In this example, the function code is indented four spaces. It doesn’t need to be four spaces, it just needs to be consistent. The first line that is not indented marks the end of the function. -
        2. In Python, an if statement is followed by a code block. If the if expression evaluates to true, the indented block is executed, otherwise it falls to the else block (if any). (Note the lack of parentheses around the expression.) +
        3. In Python, an if statement is followed by a code block. If the if expression evaluates to true, the indented block is executed, otherwise it falls to the else block (if any). Note the lack of parentheses around the expression.
        4. This line is inside the if code block. This raise statement will raise an exception (of type ValueError), but only if size < 0.
        5. This is not the end of the function. Completely blank lines don’t count. They can make the code more readable, but they don’t count as code block delimiters. The function continues on the next line.
        6. The for loop also marks the start of a code block. Code blocks can contain multiple lines, as long as they are all indented the same amount. This for loop has three lines of code in it. There is no other special syntax for multi-line code blocks. Just indent and get on with your life. @@ -248,10 +249,80 @@ SyntaxError: non-keyword arg after keyword arg

          ⁂ +

          Exceptions

          + +

          Exceptions are everywhere in Python. Virtually every module in the standard Python library uses them, and Python itself will raise them in a lot of different circumstances. You’ll see them repeatedly throughout this book. + +

          What is an exception? It’s an error, an indication that something went wrong. Some programming languages encourage the use of error return codes, which you need to check. Python encourages the use of exceptions, which you need to handle. + +

          When an error occurs in the Python Shell, it prints out some details about the exception and how it happened, and that’s that. This is called an unhandled exception. When the exception was raised, there was no code to explicitly notice it and deal with it, so it bubbled its way back up to the top level of the Python Shell, which spits out some debugging information and calls it a day. In the shell, that's no big deal, but if that happened while your actual Python program was running, the entire program would come to a screeching halt. + +

          +

          Unlike Java, Python functions don’t declare which exceptions they might raise. It’s up to you to determine what possible exceptions you need to catch. +

          + +

          An exception doesn’t need result in a complete program crash, though. Exceptions can be handled. Sometimes an exception is really because you have a bug in your code (like accessing a variable that doesn’t exist), but sometimes an exception is something you can anticipate. If you’re opening a file, it might not exist. If you’re importing a module, it might not be installed. If you’re connecting to a database, it might be unavailable, or you might not have the correct security credentials to access it. If you know a line of code may raise an exception, you should handle the exception using a try...except block. + +

          +

          Python uses try...except blocks to handle exceptions, and the raise statement to generate them. Java and C++ use try...catch blocks to handle exceptions, and the throw statement to generate them. +

          + +

          The approximate_size() function raises exceptions in two different cases: if the given size is larger than the function is designed to handle, or if it’s less than zero. + +

          if size < 0:
          +    raise ValueError('number must be non-negative')
          + +

          The syntax for raising an exception is simple enough. Use the raise statement, followed by the exception name, and an optional human-readable string for debugging purposes. The syntax is reminiscent of calling a function. (In reality, exceptions are implemented as classes, and this raise statement is actually creating an instance of the ValueError class and passing the string 'number must be non-negative' to its initialization method. But we’re getting ahead of ourselves!) + +

          Catching Import Errors

          + +

          One of Python’s built-in exceptions is ImportError, which is raised when you try to import a module and fail. This can happen for a variety of reasons, but the simplest case is when the module doesn’t exist in your import search path. You can use this to include optional features in your program. For example, the chardet library provides character encoding auto-detection. Perhaps your program wants to use this library if it exists, but continue gracefully if the user hasn’t installed it. You can do this with a try..except block. + +

          try:
          +  import chardet
          +except ImportError:
          +  chardet = None
          + +

          Later, you can check for the presence of the chardet module with a simple if statement: + +

          if chardet:
          +  # do something
          +else:
          +  # continue anyway
          + +

          Another common use of the ImportError exception is when two modules implement a common API, but one is more desirable than the other. (Maybe it’s faster, or it uses less memory.) You can try to import one module but fall back to a different module if the first import fails. For example, the XML chapter talks about two modules that implement a common API, called the ElementTree API. The first, lxml, is a third-party module that you need to download and install yourself. The second, xml.etree.ElementTree, is slower but is part of the Python 3 standard library. + +

          try:
          +    from lxml import etree
          +except ImportError:
          +    import xml.etree.ElementTree as etree
          + +

          By the end of this try..except block, you have imported some module and named it etree. Since both modules implement a common API, the rest of your code doesn’t need to keep checking which module got imported. And since the module that did get imported is always called etree, the rest of your code doesn’t need to be littered with if statements to call differently-named modules. + +

          Unbound Variables

          + +

          Take another look at this line of code from the approximate_size() function: + +

          multiple = 1024 if a_kilobyte_is_1024_bytes else 1000
          + +

          You never declare the variable multiple, you just assign a value to it. That’s OK, because Python lets you do that. What Python will not let you do is reference a variable that has never been assigned a value. Trying to do so will raise a NameError exception. +

          +>>> x
          +Traceback (most recent call last):
          +  File "<stdin>", line 1, in <module>
          +NameError: name 'x' is not defined
          +>>> x = 1
          +>>> x
          +1
          + +

          You will thank Python for this one day. + +

          ⁂ +

          Running Scripts

          Python modules are objects and have several useful attributes. You can use this to easily test your modules as you write them, by including a special block of code that executes when you run the Python file on the command line. Take the last few lines of humansize.py: -

          
          +
          
           if __name__ == '__main__':
               print(approximate_size(1000000000000, False))
               print(approximate_size(1000000000000))
          @@ -259,12 +330,12 @@ if __name__ == '__main__':

          Like C, Python uses == for comparison and = for assignment. Unlike C, Python does not support in-line assignment, so there’s no chance of accidentally assigning the value you thought you were comparing.

          So what makes this if statement special? Well, modules are objects, and all modules have a built-in attribute __name__. A module’s __name__ depends on how you’re using the module. If you import the module, then __name__ is the module’s filename, without a directory path or file extension. -

          +
           >>> import humansize
           >>> humansize.__name__
           'humansize'

          But you can also run the module directly as a standalone program, in which case __name__ will be a special default value, __main__. Python will evaluate this if statement, find a true expression, and execute the if code block. In this case, to print two values. -

          +
           c:\home\diveintopython3> c:\python30\python.exe humansize.py
           1.0 TB
           931.3 GiB