[Cython] Compiler error when @staticmethod is used in cdef class

Lisandro Dalcin dalcinl at gmail.com
Wed Apr 27 18:51:42 CEST 2011


On 27 April 2011 12:45, Bogdan Opanchuk <mantihor at gmail.com> wrote:
> Hello,
>
> I am using Cython 0.14.1 with Python 2.7.1 on OSX 10.6.7
>
> The following code:
> ---
> cdef class Test:
>        @staticmethod
>        def func():
>                print "Static method"
> ---
> gives error when being cythoned: "Method func has wrong number of
> arguments (0 declared, 1 or more expected)"
>
> And if one adds some parameters to this method (like "def func(a,
> b):"), cython crashes with exception:
> ---
> ... long stack trace ...
>  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/Cython-0.14-py2.7-macosx-10.6-intel.egg/Cython/Compiler/TypeSlots.py",
> line 100, in fixed_arg_type
>    return self.format_map[self.fixed_arg_format[i]]
> KeyError: 'T'
> ---
>
> So, is there a way to create static methods in cdef classes? This
> workaround seems to work, but it is a bit ugly:
> ---
> def func(a, b):
>        print "Static method"
>
> cdef class Test:
>        func = func
> ---
>
> Best regards,
> Bogdan
> _______________________________________________
> cython-devel mailing list
> cython-devel at python.org
> http://mail.python.org/mailman/listinfo/cython-devel
>

This issue has bugged my from the fist day I've started to use Cython.
However, never got time to look for a fix. Moreover, I think using
@classmethod is better than @staticmethod. @classmethod gives you some
extra context (the class) that could be useful in the case of
inheritance, specially if your method is a factory function.

So, as a workaround, try to use @classmethod, from an API point of
view they are very similar, and you can take advantage of @classmethod
extra context in the future.


-- 
Lisandro Dalcin
---------------
CIMEC (INTEC/CONICET-UNL)
Predio CONICET-Santa Fe
Colectora RN 168 Km 472, Paraje El Pozo
3000 Santa Fe, Argentina
Tel: +54-342-4511594 (ext 1011)
Tel/Fax: +54-342-4511169


More information about the cython-devel mailing list