I am trying to add a new class/type to python via C/C++. This particular class has a vector like attribute called x
, it is a list but it is made only from positive doubles. I used the tp_getset
to have finer control over setting x
when defined like:
>>> obj.x=[1.0,2.5,3.5]
I have total control over the setting of the attribute, and it works as expected and I can prevent user from doing:
>>> obj.x=[1.0,2.5,-4]
Traceback (most recent call last):
File "input.py", line 21, in <module>
obj.x=[1.0,2.5,-4]
ValueError: 'x[2]' should be greater than or equal to 0.
or
>>> obj.x=[1.0,2.5,'str']
Traceback (most recent call last):
File "input.py", line 21, in <module>
obj.x=[1.0,2.5,'str'];
TypeError: fialure to deduce C++ type <double*>
and throw an exception. However, when tp_getset.get
is defined which returns a list object of doubles, I do not have any control over the user doing the following:
>>> obj.x=[1.0,2.5,3.5]
>>> obj.x[2]=-3.6
I know that as a last resort I can just generate a list object with only one reference every time tp_getset.get
and do not keep a reference inside the class so that obj.x[2]
basically a temporary and nothing will happen
>>>obj.x=[1.0,2.5,3.5]
>>>obj.x[2]='str'
>>>print obj.x
[1.0,2.5,3.5]
My question is there a way to have this specific kind of control over sequence attributes of a class? for example.
>>> obj.x=[1.0,2.5,4]
>>> obj.x[2]=-3
File "input.py", line 21, in <module>
obj.x[2]=-3
ValueError: 'x[2]' should be greater than or equal to 0.
EDIT: I just added more details for clarification