0

I'm extending a Python ORM with an InType field, which is a validator.

In fact, I am creating a whole number of validators... in web2py DAL terms I am emulating:

Field(type=String, validators=[IS_EMAIL(), IS_IN(['foo@bar.com'])])

However doing it all at the custom field level. I've tried to create a test-case here:

from types import StringType, IntType

class StringField(object):
    def validate(self, value):
        assert type(value) is StringType
        self.value = value


class IntField(object):
    def validate(self, value):
        assert type(value) is IntType
        self.value = value

class InField(object):
    """
        Confirms `value in enumerable` before putting
        in `StringField` or `IntField`
    """

    def validate(self, value, enumerable):
        assert value not in enumerable
        obj = (StringField if type(value) is StringType else IntField)()
        obj.validate(value)
        return obj

Rather than returning an instance object of a class figured out at runtime like above, I was thinking it'd be better to implement it using metaclassing, or some other technique.

How should I approach this problem?

Community
  • 1
  • 1
A T
  • 13,008
  • 21
  • 97
  • 158
  • It's not very clear what you are trying to accomplish with InField but if you want to take a decision based on the type of a value at runtime, I can't see how a metaclass would help you. – Tasos Vogiatzoglou Mar 08 '15 at 11:54
  • Is there any approach better than mine? - IMHO this solution sucks – A T Mar 08 '15 at 12:20
  • Considering that you want decide upon runtime which validator to pick, I can't think of a much better alternative solution. You could consider multimethods specialized by field type. See https://pypi.python.org/pypi/multimethods – Tasos Vogiatzoglou Mar 08 '15 at 13:05
  • Mmm, well I don't think multimethods are the right solution here, because that would require double-typing. The initial validation is consistent irrespective of types, then it needs to call the right type. Another solution would be to use a function rather than a class, with signature `(FieldClass, value, enumerable)`. – A T Mar 08 '15 at 22:54

0 Answers0