Attribute access bug: Python subclass of cdef class

177 views
Skip to first unread message

Stefan van Zwam

unread,
Aug 29, 2012, 5:54:42 PM8/29/12
to cython...@googlegroups.com
Hi all,

Another day, another inexplicable behavior… First, the example (3 files):

# thing.pxd :
# ------
cdef class Thing:
cdef public __spea_ker

# thing.pyx :
# ------
cdef class Thing:
def __init__(self):
self.__spea_ker = 'Hey'

# subthing.py
# ------
from thing import Thing

class SubThing(Thing):
def test(self):
print self.__spea_ker

def test2(self):
print getattr(self, '__spea_ker')

In other words, a Python subclass of an extension type tries to access a public attribute of the cdef class/extension type. Now let's run it:

>>> from subthing import SubThing
>>> T = SubThing()
>>> T.test()
Traceback (most recent call last):
...
AttributeError: 'SubThing' object has no attribute '_SubThing__spea_ker'
>>> T.test2()
Hey

In other words, I can access the attribute with "getattr", but not with the dot-notation. The underscores in the attribute name play a role: without them, both test() and test2() work.

I don't know what to do with this, and have found my workaround, but figured it would be useful to leave a record somewhere in case others run into this.

Regards,

Stefan.

Stefan Behnel

unread,
Aug 29, 2012, 5:58:55 PM8/29/12
to cython...@googlegroups.com
Stefan van Zwam, 29.08.2012 23:54:
Try the same in plain Python. Class attributes that start with a double
underscore are special cased by Python (by the parser IIRC) as private
attributes, thus the name mangling.

Stefan

Stefan

unread,
Aug 31, 2012, 10:52:54 AM8/31/12
to cython...@googlegroups.com, stef...@behnel.de


Try the same in plain Python. Class attributes that start with a double
underscore are special cased by Python (by the parser IIRC) as private
attributes, thus the name mangling.

Stefan


Thanks! I remember now that I read about this when learning Python. It's still a bit weird that getattr works differently from the dot, and that I _can_ use the dot version from the interactive shell. 
Reply all
Reply to author
Forward
0 new messages