Which style is preferable?

A

Antoon Pardon

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?
 
P

Pete Shinners

Antoon said:
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
 
L

Lonnie Princehouse

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['hw', 'eo', 'lr', 'll', 'od']



Antoon Pardon said:
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?
 
T

Terry Reedy

Pete Shinners said:
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
 
A

Antoon Pardon

Op 2004-07-16 said:
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.
 
A

Antoon Pardon

Op 2004-07-16 said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,015
Latest member
AmbrosePal

Latest Threads

Top