Partial classes

Sanjay skpatel20 at hotmail.com
Wed Jul 19 04:13:26 EDT 2006


> Can you flesh out your use case a little bit and tell why you can't solve
> the problem with inheritance or a meta class?

I have to study about metaclass and see whether this can be handled. It
seemed inheritence is not working.

PROBLEM: Separating plumbing code and business logic while using
SQLAlchemy ORM.

Database script:

CREATE TABLE person (
  id SERIAL,
  passport VARCHAR(50) NOT NULL,
  blocked BOOLEAN NOT NULL DEFAULT FALSE,
  first_name VARCHAR(30) NOT NULL,
  middle_name VARCHAR(30) NULL,
  last_name VARCHAR(30) NOT NULL,
  email VARCHAR(100) NOT NULL,
  used_bytes INTEGER NOT NULL DEFAULT 0,
  PRIMARY KEY(id)
);

CREATE TABLE contact (
  person_id INTEGER NOT NULL REFERENCES person,
  contact_id INTEGER NOT NULL REFERENCES person,
  favorite BOOLEAN NOT NULL DEFAULT FALSE,
  PRIMARY KEY(person_id, contact_id)
);

DB definitions and plumbing code goes into one module, say db.py:

import sqlalchemy.mods.threadlocal
from sqlalchemy import *

global_connect('postgres://userid:password@localhost:5432/tm')
person_tbl = Table('person', default_metadata, autoload = True)
class Person(object):
    pass
contact_tbl = Table('contact', default_metadata, autoload = True)
class Contact(object):
    pass
assign_mapper(Person, person_tbl, properties = {
    'contacts' :
    relation(Contact,
primaryjoin=person_tbl.c.id==contact_tbl.c.person_id,
association=Person)
    })

assign_mapper(Contact, contact_tbl, properties = {
    'person' :
    relation(Person,
primaryjoin=person_tbl.c.id==contact_tbl.c.contact_id)
    })

Business logic in another module, say bo.py

Class PersonBO(Person):
     def Block():
          blocked = True

While using PersonBO in another module, like this:

p1 = PersonBO(passport = "skpatel20 at hotmail.com", first_name='john',
last_name='smith', email = "skpatel20 at yahoo.com")
p2 = PersonBO(passport = "skpatel20 at yahoo.com", first_name='ed',
last_name='helms', email = "skpatel20 at yahoo.com")
p3 = PersonBO(passport = "skpatel20 at yahoo.com", first_name='jonathan',
last_name='lacour', email = "skpatel20 at yahoo.com")

# add a contact
p1.contacts.append(Contact(person=p2))

the following error message occurs:

AttributeError: 'PersonBO' object has no attribute 'contacts'

What I guess, from my limited knowledge of the technologies involved,
is that assign_mapper does some magic only on Person class, and things
work. But after inheritence, it is not working.

The point in general, to my knowledge, about inheritance is that it
can't be a substitute for all the usages of partical classes. Metaclass
is a new concept for me, which I have to study.

As far as my project is concerned, I have found out some other way of
doing the things, and it is no more an issue.

Thanks a lot,
Sanjay




More information about the Python-list mailing list