## Pytyp - Extending Python Types for Declarative Code

From: andrew cooke <andrew@...>

Date: Fri, 20 May 2011 08:57:56 -0400

I finished and released v2.0 of the Pytyp package yesterday.  While I think
it's awesome, I suspect it will never be used.  Because it's not an easy thing
to "sell" - an "embedded domain specific language for type metadata" doesn't
sound very useful, does it?

But I'd encourage you to have a second look.  The main use that I see is in
producing libraries with *declarative* APIs.  Pytyp lets you describe what
data should look like.

The perfect example is converting JSON to Python classes.  Here is code using
a library built on top of pytyp:

>>> class Example():
...     def __init__(self, foo):
...         self.foo = foo
...     def __repr__(self):
...         return '<Example({0})>'.format(self.foo)

>>> class Container():
...     def __init__(self, *examples:[Example]):
...         self.examples = examples
...     def __repr__(self):
...         return '<Container({0})>'.\
...             format(','.join(map(repr, self.examples)))

<Container(<Example(abc)>,<Example(xyz)>)>

All the user needs to do is:
2 - Add type annotations to constructors (eg *examples:[Example])

That may not seem like much, but if you implement this within pytyp, which
tries to provide a consistent framework for types, you get - "for free" -
things like the possibility to express alternative types.

So if you don't know if the JSON data encodes Container or OtherClass, you can
use:

Code - http://www.acooke.org/pytyp