"D'Arcy Cain" wrote in message news:6b4b8587-46c0-19b0-c538-efdf396f0...@vybenetworks.com...

On 2018-08-14 04:58 AM, Frank Millman wrote:
> As an example, I have a master class defining a unit of data (i.e. the
> value of a column) retrieved from a database. I have separate
> sub-classes for each data type - text, integer, date, etc. To ensure
> that a value is valid before storing it as an instance attribute, I call
> a method called 'check_value'. The details of check_value vary according
> to the data type, but that is transparent to the piece of code that
> calls check_value().

class classA:
  DATATYPE = None # Or default type

  def check_value(self, v)
    if not isinstance(v, self.DATATYPE):
      raise RuntimeError("Invalid data type for '%s'" % v)

class classB(classA):
  DATATYPE = int

Very simplistic and untested but does that give you any ideas?
Hopefully your email client doesn't mess up the formatting.  You can
fill out check_value to do more than simply check the the type matches
and you can also do further checks based on the type.  Also, you can
have more than one sub-class doing the same check without having to cut
and paste code from another class.


Thanks, D'Arcy. That is a neat idea if all you want to do is check the data type, but I do a lot more than that.

How would you extend it without a long chain of
   if isinstance(v, str):
     [perform checks for str]
   elif isinstance(v, int)
     [perform checks for int]
   etc
   etc

I find that using a separate method per subclass does exactly what I want, and that part of my project has been working stably for some time.

The only thing that has changed is that I recently started using pylint (as a result of switching my editor to VS Code).

My main class has the following method (simplified) -

class Field:
   def setval(self, value):  # handle value received from external source

       """
       checkval is a method defined in each subclass
       it does a bit of typecasting, so value is replaced on return
       it can raise an exception, which is caught elsewhere
       """

value = self.checkval(value) # this is the line that pylint complains about

       [various other checks]
       if all checks are passed:
           self._value = value

Frank


--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to