The most similar example to what I want to do, I think is here:
http://groups.google.com/group/sqlalchemy/browse_thread/thread/81cc56d5ed693a48/58a3caa40a7daa39?lnk=gst&q=TypeDecorator#58a3caa40a7daa39
where Frank is storing nutrient weights in a new type.

After (re)reading the doco about custom types at:
http://www.sqlalchemy.org/docs/05/reference/sqlalchemy/types.html#sqlalchemy.types.TypeDecorator
it seems to me that the reason for using TypeDecorator rather than
TypeEngine is something to do with this sentence: "The reason that
type behavior is modified using class decoration instead of
subclassing is due to the way dialect specific types are used." I
suppose there are some complexities with bind_params implementations
across dialects. eg. http://www.sqlite.org/c3ref/bind_blob.html

In Frank's example he defined two classes: Weight(Object) and
WeightType(types.TypeDecorator) but it still seems more natural to me
to use the subclassing of TypeEngine to create a new compound type
from two(or three) FLOATs. Then I might have to write methods
overriding adapt_operator and compare_values and copy(value) but at
least I'd understand what I was doing and why.

However as TypeDecorator seems to be the recommended way, perhaps I
should go with the flow. But what about the adapt_operator,
compare_values etc? Will that all somehow be taken care of
automagically if I do something like this? Numpy seems to have gained
quite a bit of acceptance so I want pull small objects of type
"np.array([x,y], np.float32)" straight out of the database and use
them directly. Is this possible? Is it sensible?

import numpy as np

class Vector(object):
    __slots__ = ['x', 'y']

    def __init__(self, x, y):
        self.x = x
        self.y = y
    """
    def __repr__(self):
        return np.array([x,y], np.float32)
    """
    #Both Sage and Numpy seem to prefer a list eg. V([x,y])
    #as the instantiation input rather than a python tuple.
    def __repr__(self):
        return "[%s, %s]" % (self.x, self.y)

class VectorType(types.TypeDecorator):

    impl = types.Numeric

    def process_bind_param(self, vector, dialect):
        if vector is None:
            return None
        return [vector.x, vector.y]

    def process_result_value(self, vector, dialect):
        if x is None:
            return None
        #return Vector(x, y) #or...
        return np.array([vector.x, vector.y], np.float32)



-- 
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To post to this group, send email to sqlalchemy@googlegroups.com.
To unsubscribe from this group, send email to 
sqlalchemy+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en.

Reply via email to