[Python-Dev] Type checks of instance variables

Greg Ward gward@python.net
Wed, 10 Oct 2001 22:47:36 -0400


On 10 October 2001, Andy Robinson said:
> > class Color(object):
> >     __slots__ =TypedSlots({ "r":(unsignedByte,unsignedByte(0),
> >                             "g":(unsignedByte,unsignedByte(0),
> >                             "b":(unsignedByte,unsignedByte(0),
> >                             "name":str})
> >
> 
> This sounds great.  In fact, it's almost exactly
> what we have been trying to do in reportlab/graphics for
> the last six months:  a graphical widget hierarchy
> which has to check the type of every assignment
> and maybe trigger recalculations, because it supports
> a GUI. It was one of the few occasions when I wished I
> was using Delphi instead of Python :-)  Reportlab would
> certainly be interested in a standardised framework for
> property-checking.

Allow me to plug Grouch, my attempt at a type-description language and
type-enforcement tool for Python.  See
  http://www.mems-exchange.org/software/grouch/
for some mild hype.

Grouch works by parsing type descriptions (currently found in class
docstrings) and creating an ObjectSchema instance.  An object schema
consists of:
  * a collection of atomic types (default: int, long, float, complex,
    string); all other types in the schema are built from these
  * a collection of type aliases (eg. "number" could be an alias for
    "int | float | long", or "FooBar" for "mypkg.foobar.FooBar")
  * a collection of ClassDefinition objects

A class definition, in turn, consists (mainly) of a list of instance
attributes and the type of each instance attribute.

One of the things you can do with an object schema is use it to walk an
object graph, enforcing the attribute types in the class definitions in
the schema.  The two scripts currently distributed with Grouch do just
that: gen_schema parses docstrings, creates an ObjectSchema, and pickles
it; check_data loads the pickled schema, and uses it to typecheck some
stored object graph (currently either another pickle or a ZODB).

The major things missing from Grouch right now are:
  * simple value constraints (eg. "notnone", "notempty")
  * fancy value constraints (eg. "oneof")
  * any knowledge of new-style classes, eg. the __slots__ attribute

I would love for some other python-dev'ers to download Grouch and give
it a look.  In my non-at-all-humble opinion, Grouch is damned neat and
provides a lot of cool ideas for anyone interested in deep, rigorous
type-checking of Python objects.

        Greg
-- 
Greg Ward - Unix bigot                                  gward@python.net
http://starship.python.net/~gward/
All programmers are playwrights and all computers are lousy actors.