Wednesday, April 16, 2008

Contract verification in Python



import zope.interface.verify

class ITest(zope.interface.Interface):
def foo(arg1): pass
def bar(): pass

class Test(object):
zope.interface.implements(ITest)
def foo(self): pass

class Test2(object):
zope.interface.implements(ITest)
def foo(self, arg1): pass

class Test3(object):
zope.interface.implements(ITest)
def foo(self, arg1): pass
def bar(self): pass

for cls in (Test, Test2, Test3):
try:
if zope.interface.verify.verifyClass(ITest, cls):
print "OK: %s correctly implements %s" % (cls.__name__, ITest.__name__)
except Exception, err:
print "Error detected with %s's implementation: %s" % (cls.__name__, err)

Getting older, getting better and better!

Python programming is joy. I was stuck on python 2.3 at my work for long and could not really get chance to explore later versions. Now that I got the opportunity doing re-architecture of the product I started exploring these. I am more than excited looking at deque, groupby, defaultdict and much more ... Also on top of it there exist excellent python softwares like twisted, sqlalchemy, turbogears makes it even more cool.
It's little pity that the language is stll somewhat less recognized than others. Or there are more hyped languages exist.

Anyways Python rocks!

SQLAlchemy elixir: Simple example

DB Setup
[root@localhost ~]# yum -y install postgresql-python \
postgresql postgresql-server
[root@localhost ~]# /etc/init.d/postgresql start
[root@localhost ~]# /etc/init.d/postgresql status
[root@localhost ~]# su - postgres -c "createuser --createdb \
--adduser shon"
[root@localhost ~]# su - shon # normal user
[shon@localhost ]$ createdb test
[shon@localhost ]$ psql test
test=# \q


Code test_alchemy.py


from elixir import *

metadata.connect("postgres:///test")

class Movie(Entity):
has_field('title', Unicode(30))
has_field('year', Integer)
has_field('description', Unicode)

def __repr__(self): return '
' % (self.title, self.year)

metadata.create_all()

def test1():
m1 = Movie(title="Blade Runner", year=1982)
m2 = Movie(title="Life is beautiful", year=1980)
objectstore.flush()
print m1

def test2():
print Movie.select()[0]

test1()
# test2()