robertwb / issues-import-test

0 stars 0 forks source link

req: support cdef class attrib initialisation #44

Open robertwb opened 8 years ago

robertwb commented 8 years ago

Reported by rebirth on 18 Jun 2008 20:26 UTC 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).

Migrated-From: http://trac.cython.org/ticket/18

robertwb commented 8 years ago

Comment by robertwb on 16 Jul 2008 06:35 UTC 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.

robertwb commented 8 years ago

Modified by robertwb on 19 Aug 2008 04:03 UTC

robertwb commented 8 years ago

Modified by robertwb on 8 Nov 2008 22:36 UTC

robertwb commented 8 years ago

Modified by scoder on 30 Dec 2008 15:26 UTC

robertwb commented 8 years ago

Comment by scoder on 8 Mar 2009 13:18 UTC Test case is in -T18.

robertwb commented 8 years ago

Comment by haoyu on 3 Apr 2010 06:36 UTC Then do we want to support access for Foo.bar? eg.

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

print(Foo.baz)

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

robertwb commented 8 years ago

Comment by roed on 21 Mar 2013 09:29 UTC I just ran into this while working on Sage. It would be a nice feature....