[Schevo-devel] How do you get field-specs in declaration order?

Patrick K. O'Brien pobrien at orbtech.com
Thu Dec 15 08:35:42 EST 2005


Tom Locke wrote:
> 
> Hi,
> 
> In [2]:db.Person.field_spec.keys()
>   [2]:['name', 'username', 'password', 'address', 'home', 'email', 'user']
> 
> Which happens to be the exact order of declaration in the schema source
> file. I think you also use this fact to get the right values into the
> right fields from _initial. But where do you get the ordering info from?
> That info is not available via regular Python reflection is it? Do you
> parse the file?

Close, but not quite.  If you look in fieldspec.py you'll see the
following base class definition:

class FieldDefinition(object):
    """A definition of a field attached to something.

    The order of FieldDefinition instance creation is kept for the
    purposes of creating ordered dictionaries of fields, etc.
    """

    __do_not_optimize__ = True

    BaseFieldClass = None
    _counter = 0

    def __init__(self, *args, **kw):
        self.name = None
        BaseFieldClass = self.BaseFieldClass
        class _Field(BaseFieldClass):
            pass
        _Field.BaseFieldClass = BaseFieldClass
        _Field._init_kw(kw)
        _Field._init_args(args)
        _Field.__name__ = BaseFieldClass.__name__
        self.FieldClass = _Field
        self.counter = FieldDefinition._counter
        FieldDefinition._counter += 1

So what happens is that every field definition that gets created ends up
with an incremental counter attribute that can be used to sort the
fields in top-down order of appearance within the schema, since Python
calls the fieldconstructors in the order they appear within the file.

That's why field constructors are a callable - so they get called and
this counter gets updated.  A field constructor is created automatically
for each field class by the field class's metaclass (field.FieldMeta).

-- 
Patrick K. O'Brien
Orbtech       http://www.orbtech.com
Schevo        http://www.schevo.org




More information about the Schevo-devel mailing list