off not reinventing the data structure wheel unless you have to. Built-in functionality
will often prove a better choice in the end.
Make no mistake: sometimes you really do need objects that add functionality to built-
in types or do something more custom. The set classes we met, for instance, can add
custom tools not directly supported by Python today, binary search trees may support
some algorithms better than dictionaries and sets can, and the tuple-tree stack imple-
mentation was actually faster than one based on built-in lists for common usage pat-
terns. Moreover, graphs and permutations are something you must code on your own.
As we’ve also seen, class encapsulations make it possible to change and extend object
internals without impacting the rest of your system. Although subclassing built-in types
can address much of the same goals, the end result is still a custom data structure.
Yet because Python comes with a set of built-in, flexible, and optimized datatypes, data
structure implementations are often not as important in Python as they are in lesser-
equipped and lower-level programming languages. Before you code that new datatype,
be sure to ask yourself whether a built-in type or call might be more in line with the
Python way of thinking.
For more on extended data structures for use in Python, see also the relatively new
collections module in its standard library. As mentioned in the preceding chapter, this
module implements named tuples, ordered dictionaries, and more. It’s described in
Python’s library manual, but its source code, like much in the standard library, can
serve as a source of supplemental examples as well.
PyTree: A Generic Tree Object Viewer
This chapter has been command line–oriented. To wrap up, I want to refer you to a
program that merges the GUI technology we studied earlier in the book with some of
the data structure ideas we’ve explored here.
This program is called PyTree—a generic tree data structure viewer written in Python
with the tkinter GUI library. PyTree sketches out the nodes of a tree on-screen as boxes
connected by arrows. It also knows how to route mouse clicks on drawn tree nodes
back to the tree, to trigger tree-specific actions. Because PyTree lets you visualize the
structure of the tree generated by a set of parameters, it’s an arguably fun way to explore
tree-based algorithms.
PyTree supports arbitrary tree types by “wrapping” real trees in interface objects. The
interface objects implement a standard protocol by communicating with the underlying
tree object. For the purposes of this chapter, PyTree is instrumented to display binary
search trees; for the next chapter, it’s also set up to render expression parse trees. New
trees can be viewed by coding wrapper classes to interface to new tree types.
1402 | Chapter 18: Data Structures