cclass while keeping dynamic attributes

21 views
Skip to first unread message

iurly

unread,
Mar 13, 2018, 1:15:44 AM3/13/18
to cython-users
Hi,

I just started using Cython, so please forgive me if it's rather a newbie question.

I'm trying to optimize the critical path of an existing program, but I would also like to keep python compatibility, so I'm trying to work in pure-python mode.
Essentially I have a few classes calling each other's methods, and I'd like the most called ones to be as optimized
as possible, avoiding dictionary lookups and python calls.
So I'm declaring those classes as @python.cclass -- however, this forces me to declare each and every variable, essentially ending up with something like this:

-------------
import cython

@cython.cclass
class A:
  cython.declare(critical=B)
  ###
  cython.declare(noncritical=object)
  ### ^^^^^^^^^^^^^^^^
  ### I would like to avoid this!
  def __init__(self):
    self.noncritical = "Cython shouldn't care"
    self.critical = B()

  def method1(self):
    self.critical.method2()
   
   
@cython.cclass
class B:
  cython.declare(x=cython.int)
  ###
  #cython.declare(noncritical=object)
  ### ^^^^^^^^^^^^^^^^
  ### I would like to avoid this!
  def __init__(self):
    self.x = 0
    self.noncritical = "Yet it does"
  @cython.cfunc
  def method2(self):
    self.x += 1
-----------

If I comment out the "cython.declare(noncritical=object)" above, I get the following error:
AttributeError: 'mixedtest.B' object has no attribute 'noncritical'

Is there any way I can get away without declaring each and every variable?
What am I doing wrong?
Thanks!

Stefan Behnel

unread,
Mar 13, 2018, 1:24:50 AM3/13/18
to cython...@googlegroups.com
>Is there any way I can get away without declaring *each and every*
>variable?

Well, the reason why cdef classes are fast is exactly that they know their attributes at compile time. It's similar to slots in Python.

But you can add a catch-all attribute dict to the class by declaring an attribute "__dict__" of type dict to make these classes behave more like Python classes again. Including the risk of typos, obviously.

Stefan
Reply all
Reply to author
Forward
0 new messages