__getattr__ on non-instantiated class

bruno at modulix onurb at xiludom.gro
Wed May 3 12:54:51 EDT 2006


Fredp wrote:
(snip)

> I have something like a simple ORM which objects haven't a fixed number
> of fields, and I need to have properties (or methods) for each of them,

dumbiest possible example, but this should het you started

class Field(object):
  # dummy
  def __init__(self, **kw):
    self.__dict__.update(kw)

class SomeORMObject(object):
  # this is a class property
  fields = {'toto' : Field(type='int', primary=True),
            'tata' : Field(type='varchar', maxlen=255, default=''),
            }

  # this is a class method,
  # the first param is the class object
  @classmethod
  def get_field(cls, fldname):
    return cls.fields.get(fldname, None)


SomeORMObject.get_field('toto')

Properties won't probably cut it, but you can write custom descriptors
(google or search python.org for a description of what descriptors are -
for the record, properties are a kind of descriptor). I did use this
kind of stuff for an 'object/ldap mapper', using descriptors for ldap
attributes and some classmethod for building queries etc...

> but currently it is more comfortable for me to use uninstantiaded
> classes (as someway SQLObject does).
> I guess I'd better taking another approach to him, maybe using
> something from ASPN cookbook :-\

Your approach is quite sensible IMHO - minus one detail : you should
avoid reinventing the Square Wheel(tm). There already are some Python
orms. I'm not found of SQLObject, but I've played a bit with SQLAlchemy
and it seems quite promising.

HTH
-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list