473,473 Members | 1,723 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

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 1250
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: SungSoo, Han | last post by:
There are two coding style when python import module. (1) import sys (2) from import sys (or from import *) I prefer (1) style. Because it's easy to read, understand module in any category .. ...
12
by: Jane Austine | last post by:
Please see the following code: -------------------------------- class rev_wrap(object): def __init__(self,l): self.l=l def __getitem__(self,i): return self.l class rev_subclass(list): def...
13
by: arreeess | last post by:
i wont used three styles in the element of a list; i have does so: <ul> <li> ............................. </li> first style <li> <p> .....................</p> </li> 2° style <li> <p...
17
by: lawrence | last post by:
How is it possible that the question "How do I detect which browser the user has" is missing from this FAQ: http://www.faqts.com/knowledge_base/index.phtml/fid/125 and is only here on this...
13
by: Gunnar | last post by:
Hello, I am running into problems with a simple function which should change the style.display properties from 'block' to 'none'. I am able to change them from 'none' to 'block' as expected. ...
5
by: STeve | last post by:
Hey guys, I currently have a 100 page word document filled with various "articles". These articles are delimited by the Style of the text (IE. Heading 1 for the various titles) These articles...
0
by: greg.landrum | last post by:
Hi, I have a fairly sizable body of python code that I'm in the process of modernizing. One of the modernization steps is converting to use new-style classes, and this is leading to problems...
5
by: =?Utf-8?B?Z3V5?= | last post by:
I find the Generic collection classes really usefull, so usefull in fact that I do not usually use the old style collections like ArrayList and Hashtable. In fact if I did need a collection of...
55
by: aarklon | last post by:
Hi all, I was going through the book "C Elements of style" by steve oualline. in this book many guidelines are given. the following were seen in the book as rules 1) while(1) is preferred...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.