[storm] Type checking

Gustavo Niemeyer gustavo at niemeyer.net
Tue Feb 17 23:09:49 GMT 2009


Hey Vernon,

> Okay, I'm sold. Type conversions should not be implicit. What's the neatest
> way to make them explicit?
>
> I am initiating the Vernon's Storm Programming Challenge
>
> (The winner will receive immortal glory and a gift certificate for a Big
> Mac.)

Thanks.  I'm willing to donate my prize if I get to it. ;-)

(...)
> In a sports database, I want to make a column 'superbowl' which gets and
> gives data of class 'roman'.

Interestingly enough, this could be a debatable case in the sense of
automatic coercion from integers specifically not being so
problematic.  Your roman class is actually a subclass of int, and
behaves as an int on all its operations except for its representation
when stringified.  I would personally not mind to coerce from ints in
this specific case when assigning to the column.

> How do I implement it in storm?

In any case, I'll show you a strict example for the sake of demonstration.

If you want to store values of type "roman" in a column in a way that
doesn't accept other types, with it being represented as an integer in
the database side, here is an untested excerpt to get you going.
Hopefully it even works.

from storm.properties import Variable, SimpleProperty

class RomanVariable(Variable):

    @staticmethod
    def parse_set(self, value, from_db):
        if from_db:
            return roman.roman(value)
        elif not isinstance(value, roman.roman):
            raise TypeError("Expected roman, got %r: %r" % (type(value), value))
        return value

    @staticmethod
    def parse_get(self, value, to_db):
        if to_db:
            return int(value)
        return value

class Roman(SimpleProperty):
    variable_class = RomanVariable


class YourClass(object):
    ...
    superbowl = Roman()


-- 
Gustavo Niemeyer
http://niemeyer.net



More information about the storm mailing list