Opened 8 years ago

Last modified 3 years ago

#18 new enhancement

req: support cdef class attrib initialisation

Reported by: rebirth@… Owned by: somebody
Priority: major Milestone: wishlist
Component: Code Generation Keywords: class attribute initialisation
Cc: biahaoyu@…


A common Python programming style is for classes to be configured via initialised class attributes, which allows users to create subclasses with different initial values, for example:

class Foo:
   bar = 5
   baz = "someval"

class MyFoo(Foo):
   bar = 7
   baz = "anotherval"

However, this does not presently work with Cython/Pyrex?.

This filing is a request for support of initialised cdef class attributes, eg:

cdef class Foo:
    cdef public int bar = 5
    cdef public object baz = "someval"
cdef class MyFoo(Foo):
    cdef public int bar = 7
    cdef public object baz = "anotherval"
class AnotherFoo(Foo):
    bar = 8
    baz = "yetanotherval"

In this example, we subclass Foo twice - once with an extension subclass containing initialised cdef class attributes, and the other as a pure-python subclass containing initialised class attributes in pure-python syntax.

Ideally, both idioms would be supported. In the former case, the int value 7 would be written to the attribute 'bar' prior to init, and in the latter case, the int object 8 would be converted to a C integer then written to the attribute bar.

The advantage of supporting these cdef class attribute initialisations is that it would allow users to stick with the python idiom of 'initialised class attributes as configuration option', while allowing the speed advantage of struct-level attribute access (as opposed to the slower getattr at the pure-python level).

Change History (7)

comment:1 Changed 8 years ago by robertwb

I've been looking at this and it's a bit tricky because one must create different defaults for the various classes (which all share the same entry object). Of course it can still be done, this is just something to watch out for.

comment:2 Changed 8 years ago by robertwb

  • Milestone set to

comment:3 Changed 8 years ago by robertwb

  • Milestone changed from 0.10 to 0.11

comment:4 Changed 7 years ago by scoder

  • Milestone changed from 0.11 to wishlist

comment:5 Changed 7 years ago by scoder

Test case is in -T18.

comment:6 Changed 6 years ago by haoyu

  • Cc biahaoyu@… added

Then do we want to support access for eg.

cdef class Foo:
    cdef public int bar = 5
    cdef public object baz = "someval"


This is supported for pure Python, it would be more intuitive if cdef class also support it.

comment:7 Changed 3 years ago by roed

I just ran into this while working on Sage. It would be a nice feature....

Note: See TracTickets for help on using tickets.