Text
stringlengths
1
9.41k
The newer and preferred sys.exc_info() call available in both 2.6 and 3.0 instead keeps track of each thread’s exception information, and so is threadspecific.
Of course, this distinction matters only when using multiple threads in Python programs (a subject beyond this book’s scope), but 3.0 forces the issue.
See other resources for more details. ###### Exception Design Tips and Gotchas I’m lumping design tips and gotchas together in this chapter, because it turns out that the most common gotchas largely stem from design issues.
By and large, exceptions are easy to use in Python. The real art behind them is in deciding how specific or general your except clauses should be and how much code to wrap up in try statements.
Let’s address the second of these concerns first. ###### What Should Be Wrapped In principle, you could wrap every statement in your script in its own `try, but that` would just be silly (the try statements would then need to be wrapped in try statements!).
What to wrap is really a design issue that goes beyond the language itself, and it will become more apparent with use.
But for now, here are a few rules of thumb: - Operations that commonly fail should generally be wrapped in try statements.
For example, operations that interface with system state (file opens, socket calls, and the like) are prime candidates for trys. - However, there are exceptions to the prior rule—in a simple script, you may _want failures of such operations to kill your program instead of being caught and_ ignored.
This is especially true if the failure is a showstopper.
Failures in Python typically result in useful error messages (not hard crashes), and this is often the best outcome you could hope for. - You should implement termination actions in try/finally statements to guarantee their execution, unless a context manager is available as a with/as option.
The try/ ``` finally statement form allows you to run code whether exceptions occur or not ``` in arbitrary scenarios. - It is sometimes more convenient to wrap the call to a large function in a single ``` try statement, rather than littering the function itself with many try statements. ``` That way, all excep...
Servers, for instance, must generally keep running persistently **|** ----- and so will likely require `try statements to catch and recover from exceptions.
In-` process testing programs of the kind we saw in this chapter will probably handle exceptions as well.
Simpler one-shot scripts, though, will often ignore exception handling completely because failure at any step requires script shutdown. ###### Catching Too Much: Avoid Empty except and Exception On to the issue of handler generality.
Python lets you pick and choose which exceptions to catch, but you sometimes have to be careful to not be too inclusive.
For example, you’ve seen that an empty except clause catches every exception that might be raised while the code in the try block runs. That’s easy to code, and sometimes desirable, but you may also wind up intercepting an error that’s expected by a try handler higher up in the exception nesting structure. For example...
# IndexError is raised in here except: ...
# But everything comes here and dies! try: func() except IndexError: # Exception should be processed here ... ``` Perhaps worse, such code might also catch unrelated system exceptions.
Even things like memory errors, genuine programming mistakes, iteration stops, keyboard interrupts, and system exits raise exceptions in Python.
Such exceptions should not usually be intercepted. For example, scripts normally exit when control falls off the end of the top-level file. However, Python also provides a built-in sys.exit(statuscode) call to allow early terminations.
This actually works by raising a built-in SystemExit exception to end the program, so that try/finally handlers run on the way out and special types of programs can intercept the event.[*] Because of this, a try with an empty except might unknowingly prevent a crucial exit, as in the following file (exiter.py): ``` i...
It is usually only used in spawned child processes, a topic beyond this book’s scope.
See the library manual or follow-up texts for details. **|** ----- ``` print('continuing...') % python exiter.py got it continuing... ``` You simply might not expect all the kinds of exceptions that could occur during an operation.
Using the built-in exception classes of the prior chapter can help in this particular case, because the Exception superclass is not a superclass of SystemExit: ``` try: bye() except Exception: # Won't catch exits, but _will_ catch many others ... ``` In other cases, though, this scheme is no better ...
Consider this code, for example: ``` mydictionary = {...} ... try: x = myditctionary['spam'] # Oops: misspelled except: x = None # Assume we got KeyError ...continue here with x... ``` The coder here assumes that the only sort of error that can happen when indexing a dictionary is a missin...
But because the name myditctionary is misspelled (it should say mydictionary), Python raises a NameError instead for the undefined name reference, which the handler will silently catch and ignore.
The event handler will incorrectly fill in a default for the dictionary access, masking the program error. Moreover, catching Exception here would have the exact same effect as an empty except.
If this happens in code that is far removed from the place where the fetched values are used, it might make for a very interesting debugging task! As a rule of thumb, be as specific in your handlers as you can be—empty except clauses and Exception catchers are handy, but potentially error-prone.
In the last example, for instance, you would be better off saying `except KeyError: to make your intentions` explicit and avoid intercepting unrelated events.
In simpler scripts, the potential for problems might not be significant enough to outweigh the convenience of a catchall, but in general, general handlers are generally trouble. **|** ----- ###### Catching Too Little: Use Class-Based Categories On the other hand, neither should handlers be too specific.
When you list specific exceptions in a try, you catch only what you actually list.
This isn’t necessarily a bad thing, but if a system evolves to raise other exceptions in the future, you may need to go back and add them to exception lists elsewhere in your code. We saw this phenomenon at work in the prior chapter.
For instance, the following handler is written to treat MyExcept1 and MyExcept2 as normal cases and everything else as an error.
Therefore, if you add a MyExcept3 in the future, it will be processed as an error unless you update the exception list: ``` try: ... except (MyExcept1, MyExcept2): # Breaks if you add a MyExcept3 ...
# Non-errors else: ... # Assumed to be an error ``` Luckily, careful use of the class-based exceptions we discussed in Chapter 33 can make this trap go away completely.
As we saw, if you catch a general superclass, you can add and raise more specific subclasses in the future without having to extend except clause lists manually—the superclass becomes an extendible exceptions category: ``` try: ... except SuccessCategoryName: # OK if I add a myerror3 subclass ...
# Non-errors else: ... # Assumed to be an error ``` In other words, a little design goes a long way.
The moral of the story is to be careful to be neither too general nor too specific in exception handlers, and to pick the granularity of your try statement wrappings wisely.
Especially in larger systems, exception policies should be a part of the overall design. ###### Core Language Summary Congratulations!
This concludes your look at the core Python programming language. If you’ve gotten this far, you may consider yourself an Official Python Programmer (and should feel free to add Python to your résumé the next time you dig it out).
You’ve already seen just about everything there is to see in the language itself, and all in much more depth than many practicing Python programmers initially do.
You’ve studied built-in types, statements, and exceptions, as well as tools used to build up larger program units (functions, modules, and classes); you’ve even explored important design issues, OOP, program architecture, and more. **|** ----- ###### The Python Toolset From this point forward, your future Python c...
You’ll find this to be an ongoing task. The standard library, for example, contains hundreds of modules, and the public domain offers still more tools.
It’s possible to spend a decade or more seeking proficiency with all these tools, especially as new ones are constantly appearing (trust me on this!). Speaking generally, Python provides a hierarchy of toolsets: _Built-ins_ Built-in types like strings, lists, and dictionaries make it easy to write simple programs fas...
We’ve only covered the first two of these categories in this book, and that’s plenty to get you started doing substantial programming in Python. Table 35-1 summarizes some of the sources of built-in or existing functionality available to Python programmers, and some topics you’ll probably be busy exploring for the rem...
Up until now, most of our examples have been very small and self-contained. They were written that way on purpose, to help you master the basics.
But now that you know all about the core language, it’s time to start learning how to use Python’s built-in interfaces to do real work.
You’ll find that with a simple language like Python, common tasks are often much easier than you might expect. _Table 35-1.
Python’s toolbox categories_ **Category** **Examples** Object types Lists, dictionaries, files, strings Functions `len, range, open` Exceptions `IndexError, KeyError` Modules `os, tkinter, pickle, re` Attributes `__dict__, __name__, __class__` Peripheral tools NumPy, SWIG, Jython, IronPython, Django, etc. **|...
For developing larger systems, a set of development tools is available in Python and the public domain. You’ve seen some of these in action, and I’ve mentioned a few others.
To help you on your way, here is a summary of some of the most commonly used tools in this domain: _PyDoc and docstrings_ PyDoc’s help function and HTML interfaces were introduced in Chapter 15.
PyDoc provides a documentation system for your modules and objects and integrates with Python’s docstrings feature. It is a standard part of the Python system—see the library manual for more details.
Be sure to also refer back to the documentation source hints listed in Chapter 4 for information on other Python information resources. _PyChecker and PyLint_ Because Python is such a dynamic language, some programming errors are not reported until your program runs (e.g., syntax errors are caught when a file is run or...
This isn’t a big drawback—as with most languages, it just means that you have to test your Python code before shipping it.
At worst, with Python you essentially trade a compile phase for an initial testing phase.
Furthermore, Python’s dynamic nature, automatic error messages, and exception model make it easier and quicker to find and fix errors in Python than it is in some other languages (unlike C, for example, Python does not crash on errors). The PyChecker and PyLint systems provide support for catching a large set of common...
They serve similar roles to the lint program in C development. Some Python groups run their code through PyChecker prior to testing or delivery, to catch any lurking potential problems.
In fact, the Python standard library is regularly run through PyChecker before release. PyChecker and PyLint are third-party open source packages; you can find them at _http://www.python.org or the PyPI website, or via your friendly neighborhood web_ search engine. _PyUnit (a.k.a.
unittest)_ In Chapter 24, we learned how to add self-test code to a Python file by using the ``` __name__ == '__main__' trick at the bottom of the file.
For more advanced testing ``` purposes, Python comes with two testing support tools.
The first, PyUnit (called ``` unittest in the library manual), provides an object-oriented class framework for ``` specifying and customizing test cases and expected results.
It mimics the JUnit framework for Java.
This is a sophisticated class-based unit testing system; see the Python library manual for details. ``` doctest ``` The doctest standard library module provides a second and simpler approach to regression testing, based upon Python’s docstrings feature.
Roughly, to use **|** ----- ``` doctest, you cut and paste a log of an interactive testing session into the docstrings ``` of your source files.
doctest then extracts your docstrings, parses out the test cases and results, and reruns the tests to verify the expected results.
doctest’s operation can be tailored in a variety of ways; see the library manual for more details. _IDEs_ We discussed IDEs for Python in Chapter 3.
IDEs such as IDLE provide a graphical environment for editing, running, debugging, and browsing your Python programs.
Some advanced IDEs (such as Eclipse, Komodo, NetBeans, and Wing IDE) may support additional development tasks, including source control integration, code refactoring, project management tools, and more.
See Chapter 3, the text editors page at http://www.python.org, and your favorite web search engine for more on available IDEs and GUI builders for Python. _Profilers_ Because Python is so high-level and dynamic, intuitions about performance gleaned from experience with other languages usually don’t apply to Python code...
We saw an example of the timing modules at work when com ``` paring iteration tools’ speeds in Chapter 20.
Profiling is usually your first optimization step—profile to isolate bottlenecks, then time alternative codings of them. ``` profile is a standard library module that implements a source code profiler for ``` Python; it runs a string of code you provide (e.g., a script file import, or a call to a function) and then,...
To profile interactively, import the profile module and call profile.run('code'), passing in the code you wish to profile as a string (e.g., a call to a function, or an import of an entire file).
To profile from a system shell command line, use a command of the form python -m profile main.py args... (see Appendix A for more on this format).
Also see Python’s standard library manuals for other profiling options; the cProfile module, for example, has identical interfaces to `profile but runs with less overhead, so it may be better suited to` profiling long-running programs. _Debuggers_ We also discussed debugging options in Chapter 3 (see its sidebar “Debug...
As a review, most development IDEs for Python support GUI-based debugging, and the Python standard library also includes a source code debugger module called pdb.
This module provides a command-line interface and works much like common C language debuggers (e.g., dbx, gdb). **|** ----- Much like the profiler, the pdb debugger can be run either interactively or from a command line and can be imported and called from a Python program.
To use it interactively, import the module, start running code by calling a pdb function (e.g., ``` pdb.run("main()")), and then type debugging commands from pdb’s interactive ``` prompt.
To launch pdb from a system shell command line, use a command of the form python -m pdb main.py args...
(see Appendix A for more on this format). _pdb also includes a useful postmortem analysis call,_ `pdb.pm(), which starts the` debugger after an exception has been encountered. Because IDEs such as IDLE also include point-and-click debugging interfaces, _pdb isn’t a critical a tool today, except when a GUI isn’t availab...
See Chapter 3 for tips on using IDLE’s debugging GUI interfaces. Really, neither pdb nor IDEs seem to be used much in practice—as noted in Chapter 3, most programmers either insert print statements or simply read Python’s error messages (not the most high-tech of approaches, but the practical tends to win the day in th...
In addition, we learned in Chapter 2 that Python programs may be shipped in their source (.py) or byte code (.pyc) forms, and that import hooks support special packaging techniques such as automatic extraction of .zip files and byte code encryption. We also briefly met the standard library’s distutils modules, which pr...
The emerging Python “eggs” third-party packaging system provides another alternative that also accounts for dependencies; search the Web for more details. _Optimization options_ There are a couple of options for optimizing your programs.
The Psyco system described in Chapter 2 provides a just-in-time compiler for translating Python byte code to binary machine code, and Shedskin offers a Python-to-C++ translator.
You may also occasionally see .pyo optimized byte code files, generated and run with the -O Python command-line flag (discussed in Chapters 21 and 33); because this provides a very modest performance boost, however, it is not commonly used. As a last resort, you can also move parts of your program to a compiled languag...
In general, Python’s speed also improves over time, so be sure to upgrade to the faster releases when possible. **|** ----- _Other hints for larger projects_ We’ve met a variety of language features in this text that will tend to become more useful once you start coding larger projects.
These include module packages (Chapter 23), class-based exceptions (Chapter 33), class pseudoprivate attributes (Chapter 30), documentation strings (Chapter 15), module path configuration files (Chapter 21), hiding names from `from * with` `__all__ lists and` `_X-style names` (Chapter 24), adding self-test code with th...
At this point, you’ve been exposed to the full subset of Python that most programmers use.
In fact, if you have read this far, you should feel free to consider yourself an official Python programmer. Be sure to pick up a t-shirt the next time you’re online. The next and final part of this book is a collection of chapters dealing with topics that are advanced, but still in the core language category.
These chapters are all optional _reading, because not every Python programmer must delve into their subjects; indeed,_ most of you can stop here and begin exploring Python’s roles in your application domains.
Frankly, application libraries tend to be more important in practice than advanced (and to some, esoteric) language features. On the other hand, if you do need to care about things like Unicode or binary data, have to deal with API-building tools such as descriptors, decorators, and metaclasses, or just want to dig a ...
The larger examples in the final part will also give you a chance to see the concepts you’ve already learned being applied in more realistic ways. As this is the end of the core material of this book, you get a break on the chapter quiz— just one question this time.
As always, though, be sure to work through this part’s closing exercises to cement what you’ve learned in the past few chapters; because the next part is optional reading, this is the final end-of-part exercises session.
If you want to see some examples of how what you’ve learned comes together in real scripts drawn from common applications, check out the “solution” to exercise 4 in Appendix B. **|** ----- ###### Test Your Knowledge: Quiz 1.
(This question is a repeat from the first quiz in Chapter 1—see, I told you it would be easy!
:-) Why does “spam” show up in so many Python examples in books and on the Web? ###### Test Your Knowledge: Answers 1.
Because Python is named after the British comedy group Monty Python (based on surveys I’ve conducted in classes, this is a much-too-well-kept secret in the Python world!).
The spam reference comes from a Monty Python skit, where a couple who are trying to order food in a cafeteria keep getting drowned out by a chorus of Vikings singing a song about spam. No, really.
And if I could insert an audio clip of that song here, I would.... ###### Test Your Knowledge: Part VII Exercises As we’ve reached the end of this part of the book, it’s time for a few exception exercises to give you a chance to practice the basics.
Exceptions really are simple tools; if you get these, you’ve probably mastered exceptions. See “Part VII, Exceptions and Tools” on page 1130 in Appendix B for the solutions. 1. try/except.
Write a function called oops that explicitly raises an IndexError exception when called. Then write another function that calls oops inside a try/except statement to catch the error.