[C++-sig] Re: Disallow adding attributes to wrapped classes from Python

Stefan Haller haller at ableton.com
Mon Dec 13 20:38:20 CET 2004


David Abrahams <dave at boost-consulting.com> wrote:

> Naw, you're right.  Are you willing to use the Boost CVS?

Not easily, sorry.  And I'm not sure if the feature is important enough
for us to go to the trouble, and to waste your time on it.

(But I could easily use a patch if it can be applied against the 1.32.0
 release; I have no idea how realistic this is.)

> You could fake it, but it wouldn't work nearly as well:
> 
>    object proxy
>    = class<anything>("anything")
>       .add_property("foobar", &Foo::getFooBar, &Foo::setFooBar);
> 
>    object metaclass = proxy.attr("__class__");
> 
>    dict d = proxy().attr("__dict__");
>    d["__slots__"] = tuple();
>    scope().attr("Foo")
>       = metaclass("Foo", tuple(), d);
> 
> You'd lose the benefit of a conversion from C++ Foo to Python, for
> example.  But you might try the above anyway just to make sure I'm not
> wasting my time with the patch.

Phew.  I'm afraid I don't understand this code at all.  I tried to get
it to work for a simple test case, with the following adjustments to
make it compile (not really knowing what I was doing):

-    = class<anything>("anything")
+    = class_<Foo>("anything")

-    dict d = proxy().attr("__dict__");
+    dict d(proxy().attr("__dict__"));

But no, this doesn't work.  It *does* prevent me from adding new
attributes, but it also doesn't show the existing property (foobar),
which is not much progress.  :-)

>>> f = Foo()
>>> f.foobar
Traceback (most recent call last):
File "<string>", line 1, in ?
AttributeError: 'Foo' object has no attribute 'foobar'
>>> f.x = 1
Traceback (most recent call last):
File "<string>", line 1, in ?
AttributeError: 'Foo' object has no attribute 'x'
>>> dir(f)
['__class__', '__delattr__', '__doc__', '__getattribute__',
'__getstate__', '__hash__', '__init__', '__new__', '__reduce__',
'__repr__', '__setattr__', '__slots__', '__str__']


-- 
Stefan Haller
Ableton
http://www.ableton.com/



More information about the Cplusplus-sig mailing list