469,270 Members | 1,725 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,270 developers. It's quick & easy.

Which style is preferable?

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
Jul 18 '05 #1
5 1165
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
Jul 18 '05 #2
Why do type checking at all?

Element-wise addition will raise an exception if you're trying to add
two elements that can't be added. If you insist on type checking, then
mechanisms like implicit conversion (i.e. int->float) and overloaded
operators won't have a chance to work their magic.

PS- Try making Vector a subclass of list:

class Vector(list):
def __add__(self, other):
return Vector([ a + b for a, b in zip(self, other)])
x = Vector([1.0, 2.0, 3.0])
y = Vector([4.0, 5.0, 6.0])
x + y [5.0, 7.0, 9.0]

# Since we're not type checking, we can add a list to a vector: Vector([1.0, 2.0]) + [100, 200] [101.0, 202.0]

# And we can do all sort of other novel things Vector('hello') + Vector('world')
['hw', 'eo', 'lr', 'll', 'od']

Antoon Pardon <ap*****@forel.vub.ac.be> wrote in message news:<sl********************@trout.vub.ac.be>... 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?

Jul 18 '05 #3

"Pete Shinners" <pe**@shinners.org> wrote in message
news:cd**********@sea.gmane.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.


I have 3 minor comments on the original code:
self.val = [ el for el in iter ] list(iter) is clearer and, I believe, faster
raise TypeError I recomment the addition of an informative error message to all raises.
if len(self.val) != term.val:

You left something out here...

However, Pete's replacement code is, in my opinion too, much better, even
with these edits.

Terry J. Reedy

Jul 18 '05 #4
Op 2004-07-16, Lonnie Princehouse schreef <fi**************@gmail.com>:
Why do type checking at all?

Element-wise addition will raise an exception if you're trying to add
two elements that can't be added. If you insist on type checking, then
mechanisms like implicit conversion (i.e. int->float) and overloaded
operators won't have a chance to work their magic.

PS- Try making Vector a subclass of list:

class Vector(list):
def __add__(self, other):
return Vector([ a + b for a, b in zip(self, other)])


I don't thing making Vector a subclass of list is a good
idea. The '+' operator is totally different for lists
and vectors. If python would use a different symbol
for concatenation, I probably would try it like this,
but now I feel it will create too much confusion.

--
Antoon Pardon
Jul 18 '05 #5
Op 2004-07-16, Pete Shinners schreef <pe**@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
Jul 18 '05 #6

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

5 posts views Thread by SungSoo, Han | last post: by
12 posts views Thread by Jane Austine | last post: by
13 posts views Thread by arreeess | last post: by
13 posts views Thread by Gunnar | last post: by
reply views Thread by greg.landrum | last post: by
5 posts views Thread by =?Utf-8?B?Z3V5?= | last post: by
55 posts views Thread by aarklon | last post: by
1 post views Thread by CARIGAR | last post: by
reply views Thread by zhoujie | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.