Which style is preferable?

Antoon Pardon apardon at forel.vub.ac.be
Mon Jul 19 04:55:31 EDT 2004


Op 2004-07-16, Pete Shinners schreef <pete at shinners.org>:
> Antoon Pardon wrote:
>> For the sake of this question I'm writing a vector class. So
>> I have code something like the following
>
> I find all the type checking a touch ugly, but perhaps I've been using 
> Python for too long. I would approach it like this.
>
>
> class Vector:
>      def __init__(self, iterable):
>          self.val = map(float, iterable)
>
>      def __add__(self, term):
>          values = map(operator.add, self.val, term)
>          return Vector(values)
>
>      def __iter__(self):
>          return self.val
>
> This will still give you a TypeError if non-float-compatible values are 
> passed. You will still get a TypeError if the add function gets an 
> object/Vector with odd types or the wrong size. One benefit, besides 
> being ridiculously simple, is it accepts integers as arguments, and you 
> can do operations with vectors against lists and tuples with the same 
> number of elements.
>
>      myvec += 1, 0, 1

Well your comments are welcome and I sure will use them,
however I have the feeling you missed the forest for the
trees.

You see in your __add__ method, you know that values
will contain all floats, yet they will all get converted
to float again in the next line.

Whether you do conversion or some type checking in __init__
or something entirely different is just a detail. The problem
is that often when you add operators you know the result
doesn't need this processing again and so it is a waste
of time to call the constructor which does such things.

So I was thinking that instead of writing


  class Vector:
  
    def __init__(self, iterable):
  
      valuelist = processing(iterable)
      self.val = valuelist
  
  
    def __add__(self, term):
  
      resultlist = do_the_addtion(self, term)
      return Vector(resultlist)


One could write it like this.


  def Vector(iterable)
  
    valuelist = processing(iterable)
    return VectorType(valuelist)
  
  
  class VectorType:
  
    def __init__(self, valuelist)
  
      self.val = valuelist
  
  
    def __add__(self, term):
  
      resultlist = do_the_addtion(self, term)
      return VectorType(resultlist)


Written like this, I can eliminated a lot of processing, because
I have written do_the_addtion in such a way that processing its
result, will be like a noop. It is this construction I was
asking comments on.

-- 
Antoon Pardon



More information about the Python-list mailing list