Which style is preferable?

Antoon Pardon apardon at forel.vub.ac.be
Fri Jul 16 09:53:31 EDT 2004


For the sake of this question I'm writing a vector class. So
I have code something like the following


from types import *
import operator


  class Vector:
  
    def __init__(self, iter):
  
      self.val = [ el for el in iter ]
      for el in self.val:
        if not isinstance(el, FloatType):
          raise TypeError
  
  
    def __add__(self, term):
  
      if ! isinstance(term, Vector):
        raise TypeError
      if len(self.val) != term.val:
        raise ValueError
      resval = map(operator.add, self.val, term.val)
      return Vector(resval)


The problem I have with the above code is, that I know
that resval will contain only floats so that calling
Vector with resval will needlessly do the type checking.


So one way to solve this would be to have a helper
function like this:

  def _Vec(lst)
  
    res = Vector()
    res.value = lst
    return res


The last line of the __add__ method would then
look like this.


  return _Vec(resval)


But I'm not really satified with this solution either
because it needs a double call to generate an unchecked
Vector.


So I would prefer to write it like this:


  def Vector(iter):

    lst = [ el for el in iter ]
    for el in lst:
      if not isinstance(el, FloatType):
        raise TypeError
    return _Vec(lst)


  class _Vec(lst):

    def __init__(self, lst):
      self.val = lst

    def __add__(self, term):
  
      if ! isinstance(term, _Vec):
        raise TypeError
      if len(self.val) != term.val:
        raise ValueError
      resval = map(operator.add, self.val, term.val)
      return _Vec(resval)


The only problem with this is that it is awkward
to use with isinstance and such, so I would finaly
add the folowing:

  VectorType = _Vec


My question now is, would this be considered an acceptable
style/interface whatever to do in python?


-- 
Antoon Pardon



More information about the Python-list mailing list