typo.py - Warn of typographical errors in Python scripts

One of the most common annoyances with using Python is that it does not report typographical errors in variable names at compile time.

For example,

def compute_area(width, height):
    area = width * hieght   # oops

Another example is a typo in an attribute for a class,

class Square:
    def __init__(self, width, height):
        self.width = width
        self.hieght = height  # oops

    def compute_area(self):
        return self.width * self.height

A more subtle error is the omission of the 'self' attribute,

class Circle:

    pi = 3.14159265358

    def __init__(self, radius):
        self.radius = radius

    def compute_area():  # oops, forgot self
        return self.radius * pi   # oops, should be self.radius * self.pi

typo.py will catch all of these errors and report them:

        hieght might be used before set at line 2
        self.height might be undefined at line 7
        self might be used before set at line 9
        pi might be used before set at line 9

How It Works

typo.py does a 2-pass interpretive analysis of the script bytecode searching for undefined variables or attributes. An object is considered undefined if all of the following are true:

  1. It does not appear on the left-hand-side (LHS) of an assignment statement within the scope of the reference.
  2. It is not defined by a def or class statement.
  3. It is not defined in an imported module.
  4. It is not defined in an extension or built-in module.

It is possible to fool typo.py with dynamically generated code, e.g., using an exec statement, __getattr__, __setattr__, __import__, etc.

typo.py is compatible with Python 1.5.2 and Python 2.x

Download

You can download it here.

Copyright

typo.py is copyright © 2001, Alan E. Klietz (alank@algintech·com).
Algin Technology (utools.com)
Unlimited redistribution is permitted.