Source code examples

This is a listing of source code examples and snippets that I've saved off over the years. Most of these are extracted from or provided the idea for projects I work on, some represent useful heuristics for which I wanted to have working examples on hand, and the rest are just experimental or thought-provoking.

PseudoStructure: a fast, small-footprint data object class for Python


PseudoStructure is the base class definition for a simple Python data object that provides excellent get/set speed (comparable to attribute access on a simple class object) as well as a minimal memory footprint (marginally larger than a list or tuple containing the field values, but significantly smaller than a simple class object having the fields as attributes).

The PseudoStructure class is easy to extend — in the simplest case, just define additional __slots__. Objects can be pickled/unpickled, and nesting of objects is fully supported. All features have been tested on CPython 2.4 - 3.3.

My Variations on a (data object) theme blog article goes into much more detail on the need for and evolution of the PseudoStructure class, and presents several alternative approaches for Python data/parameter objects. You can also discuss or critique PseudoStructure at ActiveState Code Recipes.

Download or view

SourceCodeViewer: a Dojo widget for downloading and viewing source code modules


SourceCodeViewer is a Dojo widget that turns a simple anchor linked to a local or remote source code module into a download button and view/hide anchor. You can actually see this widget in action on this page; view the source to see an example of how it can be configured.

The view/hide button asynchronously downloads the source code module, highlights it, and expands to show the highlighted source inline. The SourceCodeViewer widget also degrades well since the source node is just a simple anchor tag.

While the download button below is functional, you'll want to clone the SourceCodeViewer repository from BitBucket and use the full javascript/ninthtest-dojo-api project (which includes the appropriate CommonJS packaging metadata files) if you want to incorporate it into your own Dojo build.

Download or view SourceCodeViewer.js