Weird UserArray AttributeError (bug ?)

G

George Sakkis

I came across a strange error when trying to define a settable property
for a new-style subclass of UserArray (Numeric). Here's a shorter
example that reproduces the problem:


from UserArray import UserArray
from math import hypot

class Vector(UserArray,object):
def __init__(self,x,y):
super(Vector,self).__init__((x,y))

def _fget(self): return hypot(*self)
def _fset(self, m): self *= m/self.magnitude
magnitude = property(_fget, _fset)


v = Vector(3.,4.)
print v.magnitude
# the line below prints an infinite sequence of:
# Exception exceptions.AttributeError: "can't delete attribute"
# in ignored
v.magnitude = 10


Any ideas on what's going on and if there's a workaround ?

George
 
G

George Sakkis

To answer my own question, the error is caused by the __setattr__
defined in UserArray:
def __setattr__(self,attr,value):
if attr=='shape':
self.array.shape=value
self.__dict__[attr]=value


I'm not sure though how to "undefine" __setattr__ in a subclass so that
property lookup works correctly. The furthest I got was to remove
__setattr__ from UserArray, but this is obviously unsafe if UserArray
is going to be used alone:

delattr(UserArray,'__setattr__')

class Vector(UserArray,object):
def __init__(self,x,y):
UserArray.__init__(self, (x,y))

shape = property(lambda self: self.array.shape,
lambda self,v: setattr(self.array,'shape',v))

magnitude = property(lambda self: hypot(*self),
# setting scales the vector
lambda self,magnitude: self.__imul__(magnitude/self.magnitude))


Any alternatives to get the same effect without deleting an attribute
of the superclass ?

George
 

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
474,238
Messages
2,571,193
Members
47,830
Latest member
ZacharySap

Latest Threads

Top